Skip to content

Commit defb1e6

Browse files
Merge pull request #140 from prgrms-web-devcourse-final-project/feat/#105
[Location] 외부 api 테스트 코드 작성
2 parents 2407772 + 55751ec commit defb1e6

8 files changed

Lines changed: 466 additions & 43 deletions

File tree

build.gradle.kts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ dependencies {
6161
testImplementation("org.springframework.boot:spring-boot-starter-test")
6262
testImplementation("org.springframework.security:spring-security-test")
6363
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
64+
testImplementation("com.squareup.okhttp3:mockwebserver:3.14.9") //외부 api 서버 테스트용
6465

6566
// 스프링 문서화
6667
implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.13")

src/main/java/com/back/web7_9_codecrete_be/domain/location/controller/KakaoTestController.java renamed to src/main/java/com/back/web7_9_codecrete_be/domain/location/controller/KakaoApiController.java

Lines changed: 11 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -18,65 +18,36 @@
1818
@RestController
1919
@RequestMapping("/api/v1/location/kakao")
2020
@RequiredArgsConstructor
21-
public class KakaoTestController {
21+
public class KakaoApiController {
2222

2323
private final KakaoLocalService kakaoLocalService;
2424

25-
@Operation(
26-
summary = "주변 음식점 조회(테스트)",
27-
description = "테스트용 하드코딩 좌표(서울 시청 근처)로 카카오 로컬에서 주변 음식점을 조회합니다., 하드코딩 좌표 : lat - 37.5665, lng -126.9780"
28-
)
29-
@ApiResponse(responseCode = "200", description = "조회 성공",
30-
content = @Content(schema = @Schema(implementation = KakaoLocalResponse.Document.class)))
31-
@GetMapping("/restaurants")
32-
33-
public List<KakaoLocalResponse.Document> testKakaoRestaurants() {
34-
35-
double lat = 37.5665;
36-
double lng = 126.9780;
37-
38-
return kakaoLocalService.searchNearbyRestaurants(lat, lng);
39-
}
4025

4126
@Operation(
42-
summary = "주변 음식점 조회(테스트)",
43-
description = "테스트용 좌표(서울 시청 근처)로 카카오 로컬에서 주변 음식점을 조회합니다, 좌표는 입력하면 됩니다." +
44-
"예시 : http://localhost:8080/api/v1/location/kakao/restaurant?lat=37.5665&lng=126.9780"
27+
summary = "주변 음식점 조회",
28+
description = "좌표(서울 시청 근처)로 카카오 로컬에서 주변 음식점을 조회합니다, 좌표는 입력하면 됩니다." +
29+
"예시 : http://localhost:8080/api/v1/location/kakao/restaurant?lat=37.5665&lon=126.9780"
4530
)
4631
@PostMapping("/restaurant")
4732
public List<KakaoLocalResponse.Document> KakaoRestaurants(
4833
@RequestParam double lat,
49-
@RequestParam double lng
34+
@RequestParam double lon
5035
){
51-
return kakaoLocalService.searchNearbyRestaurants(lat, lng);
36+
return kakaoLocalService.searchNearbyRestaurants(lat, lon);
5237
}
5338

54-
@Operation(
55-
summary = "주변 카페 조회(테스트)",
56-
description = "테스트용 하드코딩 좌표(서울 시청 근처)로 카카오 로컬에서 주변 카페를 조회합니다., 하드코딩 좌표 : lat - 37.5665, lng -126.9780"
57-
)
58-
@ApiResponse(responseCode = "200", description = "조회 성공",
59-
content = @Content(schema = @Schema(implementation = KakaoLocalResponse.Document.class)))
60-
@GetMapping("/cafes")
61-
public List<KakaoLocalResponse.Document> testKakaoCafes() {
62-
63-
double lat = 37.5665;
64-
double lng = 126.9780;
65-
66-
return kakaoLocalService.searchNearbyCafes(lat, lng);
67-
}
6839

6940
@Operation(
70-
summary = "주변 카페 조회(테스트)",
71-
description = "테스트용 좌표(서울 시청 근처)로 카카오 로컬에서 주변 카페를 조회합니다, 좌표는 입력하면 됩니다." +
72-
"예시 : http://localhost:8080/api/v1/location/kakao/cafes?lat=37.5665&lng=126.9780"
41+
summary = "주변 카페 조회",
42+
description = "좌표(서울 시청 근처)로 카카오 로컬에서 주변 카페를 조회합니다, 좌표는 입력하면 됩니다." +
43+
"예시 : http://localhost:8080/api/v1/location/kakao/cafes?lat=37.5665&lon=126.9780"
7344
)
7445
@PostMapping("/cafes")
7546
public List<KakaoLocalResponse.Document> KakaoCafes(
7647
@RequestParam double lat,
77-
@RequestParam double lng
48+
@RequestParam double lon
7849
){
79-
return kakaoLocalService.searchNearbyCafes(lat, lng);
50+
return kakaoLocalService.searchNearbyCafes(lat, lon);
8051
}
8152

8253

src/main/java/com/back/web7_9_codecrete_be/domain/location/controller/TmapController.java renamed to src/main/java/com/back/web7_9_codecrete_be/domain/location/controller/TmapApiController.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
@RestController
1818
@RequiredArgsConstructor
1919
@RequestMapping("/api/v1/location")
20-
public class TmapController {
20+
public class TmapApiController {
2121

2222
private final TmapService tmapService;
2323

src/main/java/com/back/web7_9_codecrete_be/global/config/WebClientConfig.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@ public class WebClientConfig {
3030
@Value("${kakao.restapi-key}")
3131
private String kakaomapApiKey;
3232

33+
@Value("${kakao.base-url}")
34+
private String kakaoBaseUrl;
35+
36+
@Value("${tmap.base-url}")
37+
private String tmapBaseUrl;
3338
@Bean
3439
public WebClient mailgunClient() {
3540
String auth = "api:" + mailgunApiKey;
@@ -58,8 +63,9 @@ public RestTemplate restTemplate() {
5863

5964
@Bean
6065
public WebClient kakaoWebClient() {
66+
6167
return WebClient.builder()
62-
.baseUrl("https://dapi.kakao.com")
68+
.baseUrl(kakaoBaseUrl)
6369
.defaultHeader("Authorization", kakaomapApiKey)
6470
.build();
6571
}
@@ -68,7 +74,7 @@ public WebClient kakaoWebClient() {
6874
@Bean
6975
public WebClient TmapClient(){
7076
return WebClient.builder()
71-
.baseUrl("https://apis.openapi.sk.com")
77+
.baseUrl(tmapBaseUrl)
7278
.defaultHeader("appKey", tmapApiKey)
7379
.build();
7480
}

src/main/resources/application.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,13 @@ jwt:
4545
refresh-token-expiration: 1209600 # 14일
4646

4747
tmap: #Tmap 대중교통 추천 api 키
48+
base-url: https://apis.openapi.sk.com
4849
api-key: ${TMAP_API_KEY}
4950

5051
kakao: #Kakao map REST API 키
52+
base-url: https://dapi.kakao.com
5153
restapi-key: ${KAKAOMAP_API_KEY}
54+
5255
kopis:
5356
api-key: ${KOPIST_API_KEY}
5457
spotify:
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
//package com.back.web7_9_codecrete_be.domain.location.controller;
2+
//
3+
//import okhttp3.mockwebserver.MockResponse;
4+
//import okhttp3.mockwebserver.MockWebServer;
5+
//import org.junit.jupiter.api.*;
6+
//import org.springframework.beans.factory.annotation.Autowired;
7+
//import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
8+
//import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
9+
//import org.springframework.context.annotation.Import;
10+
//import org.springframework.test.context.ActiveProfiles;
11+
//import org.springframework.test.context.DynamicPropertyRegistry;
12+
//import org.springframework.test.context.DynamicPropertySource;
13+
//import org.springframework.test.web.servlet.MockMvc;
14+
//
15+
//import com.back.web7_9_codecrete_be.domain.location.service.KakaoLocalService;
16+
//import com.back.web7_9_codecrete_be.global.config.WebClientConfig; // 네 프로젝트 패키지에 맞게 import 수정
17+
//
18+
//import java.io.IOException;
19+
//import java.net.URLEncoder;
20+
//import java.nio.charset.StandardCharsets;
21+
//
22+
//import static org.assertj.core.api.Assertions.assertThat;
23+
//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
24+
//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
25+
//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
26+
//@AutoConfigureMockMvc(addFilters = false)
27+
//@ActiveProfiles("test")@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
28+
//@WebMvcTest(controllers = KakaoApiController.class)
29+
//@Import({KakaoLocalService.class, WebClientConfig.class})
30+
//@TestInstance(TestInstance.Lifecycle.PER_CLASS)
31+
//class KakaoApiControllerTest {
32+
//
33+
// private static MockWebServer server;
34+
//
35+
// @Autowired
36+
// private MockMvc mockMvc;
37+
//
38+
//
39+
// @AfterAll
40+
// static void stopServer() throws IOException {
41+
// if (server != null) server.shutdown();
42+
// }
43+
//
44+
// @DynamicPropertySource
45+
// static void overrideProps(DynamicPropertyRegistry r) {
46+
// try {
47+
// if (server == null) {
48+
// server = new MockWebServer();
49+
// server.start();
50+
// }
51+
// } catch (IOException e) {
52+
// throw new RuntimeException(e);
53+
// }
54+
//
55+
// r.add("kakao.base-url", () -> server.url("/").toString());
56+
// r.add("kakao.restapi-key", () -> "KakaoAK test-key");
57+
// }
58+
//
59+
// @Test
60+
// void POST_restaurant_우리API호출하면_카카오연동을거쳐_응답이온다() throws Exception {
61+
// server.enqueue(new MockResponse()
62+
// .setResponseCode(200)
63+
// .addHeader("Content-Type", "application/json; charset=UTF-8")
64+
// .setBody("""
65+
// {
66+
// "documents": [
67+
// {
68+
// "place_name": "테스트식당",
69+
// "x": "127.0",
70+
// "y": "37.5",
71+
// "road_address_name": "서울 ...",
72+
// "address_name": "서울 ...",
73+
// "place_url": "https://place.map.kakao.com/111"
74+
// }
75+
// ]
76+
// }
77+
// """));
78+
//
79+
// mockMvc.perform(post("/api/v1/location/kakao/restaurant")
80+
// .param("lat", "37.5")
81+
// .param("lon", "127.0"))
82+
// .andExpect(status().isOk())
83+
// .andExpect(jsonPath("$[0].place_name").value("테스트식당"))
84+
// .andExpect(jsonPath("$[0].x").value("127.0"))
85+
// .andExpect(jsonPath("$[0].y").value("37.5"));
86+
//
87+
// var req = server.takeRequest();
88+
// assertThat(req.getMethod()).isEqualTo("GET");
89+
// assertThat(req.getHeader("Authorization")).isEqualTo("KakaoAK test-key");
90+
//
91+
// assertThat(req.getPath()).startsWith("/v2/local/search/keyword.json?");
92+
// String encoded = URLEncoder.encode("음식점", StandardCharsets.UTF_8);
93+
// assertThat(req.getPath()).contains("query=" + encoded);
94+
// assertThat(req.getPath()).contains("y=37.5");
95+
// assertThat(req.getPath()).contains("x=127.0");
96+
// assertThat(req.getPath()).contains("radius=1000");
97+
// assertThat(req.getPath()).contains("sort=distance");
98+
// }
99+
//
100+
// @Test
101+
// void POST_cafes_우리API호출하면_카카오연동을거쳐_응답이온다() throws Exception {
102+
// server.enqueue(new MockResponse()
103+
// .setResponseCode(200)
104+
// .addHeader("Content-Type", "application/json; charset=UTF-8")
105+
// .setBody("""
106+
// {
107+
// "documents": [
108+
// {
109+
// "place_name": "테스트카페",
110+
// "x": "126.9780",
111+
// "y": "37.5665",
112+
// "road_address_name": "서울 ...",
113+
// "address_name": "서울 ...",
114+
// "place_url": "https://place.map.kakao.com/222"
115+
// }
116+
// ]
117+
// }
118+
// """));
119+
//
120+
// mockMvc.perform(post("/api/v1/location/kakao/cafes")
121+
// .param("lat", "37.5665")
122+
// .param("lon", "126.9780"))
123+
// .andExpect(status().isOk())
124+
// .andExpect(jsonPath("$[0].place_name").value("테스트카페"))
125+
// .andExpect(jsonPath("$[0].x").value("126.9780"))
126+
// .andExpect(jsonPath("$[0].y").value("37.5665"));
127+
//
128+
// var req = server.takeRequest();
129+
// assertThat(req.getMethod()).isEqualTo("GET");
130+
// assertThat(req.getHeader("Authorization")).isEqualTo("KakaoAK test-key");
131+
//
132+
// assertThat(req.getPath()).startsWith("/v2/local/search/keyword.json?");
133+
// String encoded = URLEncoder.encode("카페", StandardCharsets.UTF_8);
134+
// assertThat(req.getPath()).contains("query=" + encoded);
135+
// assertThat(req.getPath()).contains("category_group_code=CE7");
136+
// assertThat(req.getPath()).contains("y=37.5665");
137+
// assertThat(req.getPath()).contains("x=126.9780");
138+
// assertThat(req.getPath()).contains("radius=1000");
139+
// assertThat(req.getPath()).contains("sort=distance");
140+
// }
141+
//
142+
// @Test
143+
// void GET_coord2address_우리API호출하면_RsData로주소가온다() throws Exception {
144+
// server.enqueue(new MockResponse()
145+
// .setResponseCode(200)
146+
// .addHeader("Content-Type", "application/json; charset=UTF-8")
147+
// .setBody("""
148+
// {
149+
// "documents": [
150+
// {
151+
// "road_address": { "address_name": "서울특별시 중구 세종대로 110" },
152+
// "address": { "address_name": "서울특별시 중구 태평로1가 31" }
153+
// }
154+
// ]
155+
// }
156+
// """));
157+
//
158+
// mockMvc.perform(get("/api/v1/location/kakao/coord2address")
159+
// .param("lat", "37.5665")
160+
// .param("lon", "126.9780"))
161+
// .andExpect(status().isOk())
162+
// .andExpect(jsonPath("$.status").value(200))
163+
// .andExpect(jsonPath("$.resultCode").value("OK"))
164+
// .andExpect(jsonPath("$.msg").value("좌표를 주소로 변환했습니다."))
165+
// .andExpect(jsonPath("$.data").value("서울특별시 중구 세종대로 110"));
166+
//
167+
// var req = server.takeRequest();
168+
// assertThat(req.getMethod()).isEqualTo("GET");
169+
// assertThat(req.getHeader("Authorization")).isEqualTo("KakaoAK test-key");
170+
//
171+
// assertThat(req.getPath()).startsWith("/v2/local/geo/coord2address.json?");
172+
// assertThat(req.getPath()).contains("x=126.978");
173+
// assertThat(req.getPath()).contains("y=37.5665");
174+
// }
175+
//}

0 commit comments

Comments
 (0)