시작은 일단 spring-boot-starter-test를 추가하는 것 부터, 기본적으로 있다.
@RunWith(SpringRunner.class) 랑 같이 써야 함
@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleControllerTest {
}
빈 설정 파일은 알아서 찾아 준다.
webEnvironment
MOCK: 내장 톰캣 구동 안함 목업을 이용
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void hello() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("hello cmlee"))
.andDo(print());
}
}
RANDOM_PORT, DEFINED_PORT: 내장 톰캣 사용
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SampleControllerTest {
@Autowired
TestRestTemplate testRestTemplate;
@MockBean
SampleService mockSampleService;
@Test
public void hello() throws Exception {
when(mockSampleService.getName()).thenReturn("cmleee");
String result = testRestTemplate.getForObject("/hello", String.class);
assertThat(result).isEqualTo("hello cmleee");
}
}
NONE: 서블릿 환경 제공 안함
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SampleControllerTest {
@Autowired
WebTestClient webTestClient;
@MockBean
SampleService mockSampleService;
@Test
public void hello() throws Exception {
when(mockSampleService.getName()).thenReturn("cmleee");
webTestClient.get().uri("/hello").exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("hello cmleee");
}
}
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
@SpringBootTest 애노테이션이 스프링 메인 애플리케이션을 찾아 가서 모든 빈을 스캔한 다음 테스트용 애플리케이션 컨텍스트를 만들면서 빈을 등록 그리고 mock빈이 있으면 등록 mock은 테스트 마다 독립적
콘솔을 모두 캡쳐 로그 메시지가 어디에 잘 찍혔는지로 테스트
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@MockBean
SampleService mockSampleService;
@Autowired
MockMvc mockMvc;
@Test
public void hello() throws Exception {
when(mockSampleService.getName()).thenReturn("cmleee");
mockMvc.perform(get("/hello"))
.andExpect(content().string("hello cmleee"));
assertThat(outputCapture.toString())
.contains("holoman")
.contains("skip");
}
}