โœ… @SpringBootTest

  • Spring ApplicationContext ์ „์ฒด๋ฅผ ๋กœ๋“œํ•ด ํ…Œ์ŠคํŠธ
  • ํ†ตํ•ฉ ํ…Œ์ŠคํŠธ ๋ชฉ์ 

WebEnvironment ์ข…๋ฅ˜

์˜ต์…˜์„ค๋ช…
MOCK์„œ๋ธ”๋ฆฟ ์ปจํ…Œ์ด๋„ˆ ์—†์ด MockMvc ์‚ฌ์šฉ (๊ธฐ๋ณธ๊ฐ’)
RANDOM_PORT์ž„์˜์˜ ํฌํŠธ๋กœ ๋‚ด์žฅ ์„œ๋ฒ„ ์‹คํ–‰, ์‹ค์ œ HTTP ํ…Œ์ŠคํŠธ์šฉ
DEFINED_PORTapplication.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")));
    }
}