@SpringBootTest
> @SpringBootApplication을 찾아가서 모든 BeanScan진행
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
* junit4 기준 @RunWith와 같이 사용해야함
참고 : https://developing-countries.tistory.com/50?category=1023056
org.junit.runners.model.InvalidTestClassError
org.junit.runners.model.InvalidTestClassError: Invalid test class 'com.example.studyspringboot.StudyspringbootApplicationTests': 1. No runnable methods at org.junit.runners.ParentRunner.validate(Par..
developing-countries.tistory.com
사용예제
1. WebEnvironment.MOCK : Servlet Container를 mocking해서 뜸 (내장 톰켓 미 사용)
> Dispatcher servlet에 요청을 보내는 것 을 테스트 할 수 있음
* 이때 mocking된 servlet과 interactional 하기 위해 MockMVC사용
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void hello() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("hello sangguk"))
.andDo(print());
}
}
2. WebEnvironment.RANDOM_PORT or DEFINE_PORT : 실제 test용 내장 Servlet이 뜸 (내장 톰켓 사용)
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SampleControllerTest {
@Autowired
TestRestTemplate testRestTemplate;
@Test
public void hello() throws Exception {
String result = testRestTemplate.getForObject("/hello", String.class);
assertThat(result).isEqualTo("hello sangguk");
}
}
* WebTestClient : asynchronous하게(비 동기) 동작함 > 웹클라이언트처럼 테스트 할 수 있음
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SampleControllerTest {
@Autowired
WebTestClient webTestClient;
@MockBean
SampleService mockSampleService;
@Test
public void hello() throws Exception {
when(mockSampleService.getName()).thenReturn("SANG_GUK");
webTestClient.get().uri("/hello").exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("hello SANG_GUK");
}
}
3. Controller만 정상 작동하는지 테스트 하고 싶은 경우
> @MockBean을 사용하여 service를 mocking함
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SampleControllerTest {
@Autowired
TestRestTemplate testRestTemplate;
@MockBean
SampleService mockSampleService;
@Test
public void hello() throws Exception {
when(mockSampleService.getName()).thenReturn("SANG_GUK");
String result = testRestTemplate.getForObject("/hello", String.class);
assertThat(result).isEqualTo("hello SANG_GUK");
}
}
'Spring Boot' 카테고리의 다른 글
HttpMessageConverters (0) | 2022.02.20 |
---|---|
Spring boot 단위 테스트 (0) | 2022.02.20 |
Logging (0) | 2022.02.20 |
프로파일 (0) | 2022.02.20 |
Properties 관리 (0) | 2022.02.14 |
댓글