
JUnit์ด ํ
์คํธ๋ฅผ ์คํํ ๋ Spring์ ํ
์คํธ ์ง์ ๊ธฐ๋ฅ์ ์ฌ์ฉํ๋๋ก ์ค์ ํ๋ค.
@Autowired๋ก Bean ์ฃผ์
, @SpringBootTest ๊ฐ์ ์ด๋
ธํ
์ด์
์ฌ์ฉ ๊ฐ๋ฅํ๋ค.
์ค์ ๋ด์ฅ ํฐ์บฃ์ ๋๋ค ํฌํธ๋ก ๋์์ ํ
์คํธ ํ๊ฒฝ์ ๊ตฌ์ฑํ๋ค.
REST API๋ฅผ TestRestTemplate๋ก ์ง์ ํธ์ถํด ํ
์คํธ ํ ์ ์๋ค.
๋จ์ ๋จ์ ํ
์คํธ๊ฐ ์๋๋ผ ์ค์ ์๋ฒ ๊ตฌ๋์ ํฌํจํ ํตํฉ ํ
์คํธ์ด๋ค.
Spring์์ ์ ๊ณตํ๋ HTTP ํด๋ผ์ด์ธํธ
Java ์ฝ๋์์ ๋ค๋ฅธ ์๋ฒ์ REST API๋ฅผ ํธ์ถํ ๋ ์ฐ๋ ๋๊ตฌ
-> Java ์ฝ๋๋ก HTTP ์์ฒญ ๋ณด๋ด๊ณ , ์๋ต ๋ฐ์์ ๊ฐ์ฒด๋ก ๋ณํํด์ฃผ๋ ํด๋์ค
GET, POST, PUT, DELETE ๊ฐ์ HTTP ๋ฉ์๋ ์ง์RestTemplate์ ์ ์ง๋ณด์ ๋ชจ๋WebClient ์ฌ์ฉ RestTemplate restTemplate = new RestTemplate();
// GET ์์ฒญ
String url = "https://jsonplaceholder.typicode.com/posts/1";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
System.out.println("์๋ต ์ฝ๋: " + response.getStatusCode());
System.out.println("์๋ต ๋ณธ๋ฌธ: " + response.getBody());
Spring Boot์ ํตํฉ ํ ์คํธ์ฉ HTTP ํด๋ผ์ด์ธํธ
์ผ๋ฐ RestTemplate๊ณผ ๋น์ทํ๊ฒ ๋์ํ์ง๋ง, ํ ์คํธ ํ๊ฒฝ์์ ์ฌ์ฉํ๊ธฐ ์ฝ๊ฒ ๋ง๋ค์ด์ง ํนํ ๋ฒ์
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
๊ฐ์ด ์ค์ ํ๋ฉด @Autowired๋ก ๋ฐ๋ก ์ฃผ์
๋ฐ์ ์ฌ์ฉ ๊ฐ๋ฅ
ํ
์คํธ ์๋ฒ๋ฅผ ๋์ด ๋ค,
GET, POST, PUT, DELETE ๊ฐ์ HTTP ์์ฒญ์ ๋ณด๋ด๊ณ ์๋ต์ ๋ฐ์ ์ ์๋ค.
| ๊ตฌ๋ถ | RestTemplate | TestRestTemplate |
|---|---|---|
| ๋ชฉ์ | ์ด์ยท๊ฐ๋ฐ ํ๊ฒฝ์์ ์ธ๋ถ API ํธ์ถ | ํ ์คํธ ํ๊ฒฝ์์ API ํธ์ถ ๋ฐ ๊ฒ์ฆ |
| ์ฌ์ฉ ์์น | ์ผ๋ฐ ์๋น์ค ๋ก์ง | @SpringBootTest ํตํฉ ํ
์คํธ |
| ๊ธฐ๋ณธ ํฌํธ ์ฐ๊ฒฐ | ์๋ ์ค์ ํ์ | @LocalServerPort์ ์ฐ๋ |
| ํน์ง | ๋จ์ HTTP ํธ์ถ | ํ ์คํธ์ฉ ์ธ์ฆยท์ค์ ์ด ํธ๋ฆฌ |
์ด์ ์ฝ๋์์ ์ธ๋ถ API ๋ถ๋ฅผ ๋ โ RestTemplate
ํตํฉ ํ
์คํธ์์ ๋ด API ์๋ํฌ์ธํธ ํธ์ถํ ๋ โ TestRestTemplate
์ฐ๋ฆฌ ์๋น์ค์์ ๋ค์ด๋ฒ ๋ ์จ API๋ฅผ ํธ์ถํด์, ๊ทธ ๊ฒฐ๊ณผ๋ฅผ ๊ฐ๊ณตํด ํ๋ฉด์ ๋ณด์ฌ์ค
@Service
public class WeatherService {
private final RestTemplate restTemplate = new RestTemplate();
public WeatherInfo getWeather(String city) {
return restTemplate.getForObject(
"https://api.weather.com/today?city=" + city,
WeatherInfo.class
);
}
}
์ฐ๋ฆฌ ์๋น์ค /weather API๊ฐ ์ ๋์ํ๋์ง ํ ์คํธ ์ฝ๋์์ ํ์ธํด๋ณด์
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WeatherControllerTest {
@LocalServerPort
int port;
@Autowired
TestRestTemplate restTemplate;
@Test
void ๋ ์จ_API_ํ
์คํธ() {
String url = "http://localhost:" + port + "/weather?city=Seoul";
ResponseEntity<WeatherInfo> response = restTemplate.getForEntity(url, WeatherInfo.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}
๋๋คํ๊ฒ ํ ๋น๋ ์๋ฒ ํฌํธ ๋ฒํธ๋ฅผ ์ฃผ์
restTemplate ์์ฒญ URL์ ์ฌ์ฉ๋๋ค (http://localhost:{port})