โ @SpringBootTest
- Spring ApplicationContext ์ ์ฒด๋ฅผ ๋ก๋ํด ํ ์คํธ
- ํตํฉ ํ ์คํธ ๋ชฉ์
WebEnvironment ์ข ๋ฅ
| ์ต์ | ์ค๋ช |
|---|---|
MOCK | ์๋ธ๋ฆฟ ์ปจํ ์ด๋ ์์ด MockMvc ์ฌ์ฉ (๊ธฐ๋ณธ๊ฐ) |
RANDOM_PORT | ์์์ ํฌํธ๋ก ๋ด์ฅ ์๋ฒ ์คํ, ์ค์ HTTP ํ ์คํธ์ฉ |
DEFINED_PORT | application.properties์ ์ ์๋ ํฌํธ ์ฌ์ฉ |
NONE | ์น ํ๊ฒฝ ๊ตฌ์ฑ ์์ด ํ ์คํธ (์ผ๋ฐ ๋จ์ ํ ์คํธ์ฉ) |
โ @AutoConfigureMockMvc
@SpringBootTest+@AutoConfigureMockMvc์กฐํฉ์ผ๋ก MockMvc ์๋ ์ฃผ์
@SpringBootTest
@AutoConfigureMockMvc
class MyMockMvcTests {
@Test
void testWithMockMvc(@Autowired MockMvc mvc) throws Exception {
mvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(content().string("Hello World"));
}
}โ TestRestTemplate
ํน์ง
RestTemplate๊ณผ ์ ์ฌํ ํ ์คํธ์ฉ HTTP ํด๋ผ์ด์ธํธ- ์ค์ HTTP ์์ฒญ์ ํตํด ํตํฉ ํ ์คํธ ์ํ
- WebEnvironment๊ฐ
RANDOM_PORT๋๋DEFINED_PORT์ผ ๋ ์ฌ์ฉ
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class HttpRequestTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
void greetingShouldReturnDefaultMessage() {
String body = restTemplate.getForObject("http://localhost:" + port + "/", String.class);
assertThat(body).contains("Hello, World");
}
}โ @WebMvcTest
๋ชฉ์
- MVC ์น ๊ณ์ธต๋ง ํ ์คํธํ ์ ์๋๋ก ์ฌ๋ผ์ด์ค ํ ์คํธ ํ๊ฒฝ ์ ๊ณต
@SpringBootTest๋ณด๋ค ๋น ๋ฅด๊ณ ๊ฐ๋ฒผ์
๋ก๋ ๋์ ์ปดํฌ๋ํธ
-
ํฌํจ:
@Controller,@ControllerAdvice,@JsonComponent,Converter,WebMvcConfigurer,HandlerMethodArgumentResolver -
์ ์ธ:
@Service,@Repository,@Component
์์
@WebMvcTest(GreetingController.class)
class WebMockTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private GreetingService service;
@Test
void greetingShouldReturnMessageFromService() throws Exception {
when(service.greet()).thenReturn("Hello, Mock");
this.mockMvc.perform(get("/greeting"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("Hello, Mock")));
}
}