[스프링 부트] chapter 11. 테스트
테스트
spring-boot-starter-test의존성 추가
(test scope추가)
@SpringBootTest
-
@RunWith(SpringRunner.class)와 함께 써야함
-
빈 설정 파일은? 알아서 찾음
-
webEnvironment
-
MOCK : mock servlet environment (내장 톰캣 사용 x)
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) public class SampleContorllerTest { @Autowired MockMvc mockMvc; @Test public void hello() throws Exception { mockMvc.perform(get("/hello")) .andExpect(status().isOk()) .andExpect(content().string("hello juho")) .andDo(print()); }
-
RANDOM_PORT, DEFINED_PORT (내장 톰캣 사용 o)
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class SampleContorllerTest { @Autowired TestRestTemplate testRestTemplate; @MockBean SampleService mockSampleService; @Test public void hello() throws Exception { when(mockSampleService.getName()).thenReturn("shinypillar"); String result = testRestTemplate.getForObject("/hello", String.class); assertThat(result).isEqualTo("hello shinypillar"); }
asynchronous하게 처리할 수 있는 WebClient (WebFlux)
먼저 pom.xml에 WebFlux 의존성 추가해야 함
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class SampleContorllerTest { @Autowired WebTestClient webTestClient; @MockBean SampleService mockSampleService; @Test public void hello() throws Exception { when(mockSampleService.getName()).thenReturn("shinypillar"); webTestClient.get().uri("/hello").exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo("hello shinypillar"); }
-
NONE : 서블릿 환경 제공 안함
-
@MockBean
-
ApplicationContext에 들어있는 빈을 Mock으로 만든 객체로 교환
-
모든 @Test마다 자동으로 리셋.
슬라이스 테스트
-
레이어 별로 잘라서 테스트
-
@JsonTest
-
@WebMvcTest
@RunWith(SpringRunner.class) @WebMvcTest(SampleController.class) public class SampleContorllerTest { @MockMvc SampleService mockSampleService; @Autowired MockMvc mockMvc; @Test public void hello() throws Exception { when(mockSampleService.getName()).thenReturn("shinypillar"); mockMvc.perform(get("/hello")) .andExpect(status().isOk()) .andExpect(content().string("hello shinypillar")) .andDo(print()); }
-
@WebFluxTest
-
@DataJpaTest
등등