|
| 1 | +package com.back.koreaTravelGuide.domain.ai.tour.client |
| 2 | + |
| 3 | +import com.back.koreaTravelGuide.application.KoreaTravelGuideApplication |
| 4 | +import com.back.koreaTravelGuide.domain.ai.tour.dto.InternalData |
| 5 | +import com.back.koreaTravelGuide.domain.ai.tour.dto.TourResponse |
| 6 | +import com.fasterxml.jackson.databind.ObjectMapper |
| 7 | +import org.junit.jupiter.api.BeforeEach |
| 8 | +import org.junit.jupiter.api.DisplayName |
| 9 | +import org.junit.jupiter.api.Test |
| 10 | +import org.junit.jupiter.api.extension.ExtendWith |
| 11 | +import org.springframework.beans.factory.annotation.Autowired |
| 12 | +import org.springframework.beans.factory.annotation.Value |
| 13 | +import org.springframework.boot.test.context.SpringBootTest |
| 14 | +import org.springframework.boot.test.context.TestConfiguration |
| 15 | +import org.springframework.boot.web.client.RestTemplateBuilder |
| 16 | +import org.springframework.context.annotation.Bean |
| 17 | +import org.springframework.http.HttpMethod |
| 18 | +import org.springframework.http.MediaType |
| 19 | +import org.springframework.test.context.ActiveProfiles |
| 20 | +import org.springframework.test.context.junit.jupiter.SpringExtension |
| 21 | +import org.springframework.test.web.client.MockRestServiceServer |
| 22 | +import org.springframework.test.web.client.match.MockRestRequestMatchers.method |
| 23 | +import org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo |
| 24 | +import org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess |
| 25 | +import org.springframework.web.client.RestTemplate |
| 26 | +import org.springframework.web.util.UriComponentsBuilder |
| 27 | +import java.net.URI |
| 28 | +import kotlin.test.assertEquals |
| 29 | +import kotlin.test.assertNotNull |
| 30 | +import kotlin.test.assertNull |
| 31 | + |
| 32 | +// 09.25 양현준 |
| 33 | +@ExtendWith(SpringExtension::class) |
| 34 | +// 패키지 경로에서 메인 설정을 찾지 못하는 오류를 해결하기 위해 애플리케이션 클래스를 명시. |
| 35 | +@SpringBootTest(classes = [KoreaTravelGuideApplication::class]) |
| 36 | +@ActiveProfiles("test") |
| 37 | +class TourApiClientTest { |
| 38 | + @Autowired private lateinit var restTemplateBuilder: RestTemplateBuilder |
| 39 | + |
| 40 | + @Autowired private lateinit var objectMapper: ObjectMapper |
| 41 | + |
| 42 | + @Value("\${tour.api.key}") |
| 43 | + private lateinit var serviceKey: String |
| 44 | + |
| 45 | + @Value("\${tour.api.base-url}") |
| 46 | + private lateinit var apiUrl: String |
| 47 | + |
| 48 | + private lateinit var restTemplate: RestTemplate |
| 49 | + private lateinit var mockServer: MockRestServiceServer |
| 50 | + private lateinit var tourApiClient: TourApiClient |
| 51 | + |
| 52 | + // 테스트마다 클라이언트와 Mock 서버를 새로 구성해 호출 상태를 초기화. |
| 53 | + @BeforeEach |
| 54 | + fun setUp() { |
| 55 | + restTemplate = restTemplateBuilder.build() |
| 56 | + mockServer = MockRestServiceServer.createServer(restTemplate) |
| 57 | + tourApiClient = TourApiClient(restTemplate, objectMapper, serviceKey, apiUrl) |
| 58 | + } |
| 59 | + |
| 60 | + // 첫 번째 관광 정보를 반환하는지. |
| 61 | + @DisplayName("TourApiClient - fetchTourInfo") |
| 62 | + @Test |
| 63 | + fun testReturnsFirstTourInfo() { |
| 64 | + val params = InternalData(numOfRows = 2, pageNo = 1, areaCode = "1", sigunguCode = "7") |
| 65 | + expectTourRequest(params, responseWithItems(sampleTourItem())) |
| 66 | + |
| 67 | + val result: TourResponse? = tourApiClient.fetchTourInfo(params) |
| 68 | + |
| 69 | + mockServer.verify() |
| 70 | + assertNotNull(result) |
| 71 | + assertEquals("2591792", result.contentId) |
| 72 | + assertEquals("개봉유수지 생태공원", result.title) |
| 73 | + assertEquals("7", result.sigunguCode) |
| 74 | + } |
| 75 | + |
| 76 | + // item 배열이 비어 있으면 null을 돌려주는지. |
| 77 | + @DisplayName("TourApiClient - fetchTourInfo") |
| 78 | + @Test |
| 79 | + fun testReturnsNullWhenItemsMissing() { |
| 80 | + val params = InternalData(numOfRows = 1, pageNo = 1, areaCode = "1", sigunguCode = "7") |
| 81 | + expectTourRequest(params, responseWithItems()) |
| 82 | + |
| 83 | + val result = tourApiClient.fetchTourInfo(params) |
| 84 | + |
| 85 | + mockServer.verify() |
| 86 | + assertNull(result) |
| 87 | + } |
| 88 | + |
| 89 | + // 요청 URL과 응답 바디를 미리 세팅해 Mock 서버가 기대한 호출을 검증. |
| 90 | + private fun expectTourRequest( |
| 91 | + params: InternalData, |
| 92 | + responseBody: String, |
| 93 | + ) { |
| 94 | + mockServer.expect(requestTo(buildExpectedUrl(params))) |
| 95 | + .andExpect(method(HttpMethod.GET)) |
| 96 | + .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)) |
| 97 | + } |
| 98 | + |
| 99 | + // 실제 클라이언트가 조합하는 URL과 동일한 형태를 만들어 비교한다. |
| 100 | + private fun buildExpectedUrl(params: InternalData): String = |
| 101 | + UriComponentsBuilder.fromUri(URI.create(apiUrl)) |
| 102 | + .path("/areaBasedList2") |
| 103 | + .queryParam("serviceKey", serviceKey) |
| 104 | + .queryParam("MobileOS", "WEB") |
| 105 | + .queryParam("MobileApp", "KoreaTravelGuide") |
| 106 | + .queryParam("_type", "json") |
| 107 | + .queryParam("numOfRows", params.numOfRows) |
| 108 | + .queryParam("pageNo", params.pageNo) |
| 109 | + .queryParam("contentTypeId", params.contentTypeId) |
| 110 | + .queryParam("areaCode", params.areaCode) |
| 111 | + .queryParam("sigunguCode", params.sigunguCode) |
| 112 | + .build() |
| 113 | + .encode() |
| 114 | + .toUriString() |
| 115 | + |
| 116 | + // Jackson을 활용해 테스트 응답 JSON을 손쉽게 조립한다. |
| 117 | + private fun responseWithItems(vararg items: Map<String, String>): String { |
| 118 | + val response = |
| 119 | + mapOf( |
| 120 | + "response" to |
| 121 | + mapOf( |
| 122 | + "header" to mapOf("resultCode" to "0000", "resultMsg" to "OK"), |
| 123 | + "body" to |
| 124 | + mapOf( |
| 125 | + "items" to mapOf("item" to items.toList()), |
| 126 | + ), |
| 127 | + ), |
| 128 | + ) |
| 129 | + |
| 130 | + return objectMapper.writeValueAsString(response) |
| 131 | + } |
| 132 | + |
| 133 | + // 테스트용 샘플 관광지 정의한다. |
| 134 | + private fun sampleTourItem(): Map<String, String> = |
| 135 | + mapOf( |
| 136 | + "contentid" to "2591792", |
| 137 | + "contenttypeid" to "12", |
| 138 | + "createdtime" to "20190313221125", |
| 139 | + "modifiedtime" to "20250316162225", |
| 140 | + "title" to "개봉유수지 생태공원", |
| 141 | + "addr1" to "서울특별시 구로구 개봉동", |
| 142 | + "areacode" to "1", |
| 143 | + "firstimage" to "", |
| 144 | + "firstimage2" to "", |
| 145 | + "mapx" to "126.8632141714", |
| 146 | + "mapy" to "37.4924524597", |
| 147 | + "mlevel" to "6", |
| 148 | + "sigungucode" to "7", |
| 149 | + "lDongRegnCd" to "11", |
| 150 | + "lDongSignguCd" to "530", |
| 151 | + ) |
| 152 | + |
| 153 | + // 테스트에서 RestTemplateBuilder 빈을 보장해 컨텍스트 로딩 실패 해결. |
| 154 | + @TestConfiguration |
| 155 | + class TestConfig { |
| 156 | + @Bean |
| 157 | + fun restTemplateBuilder(): RestTemplateBuilder = RestTemplateBuilder() |
| 158 | + } |
| 159 | +} |
0 commit comments