mock을 이용한 간단한 테스트를 진행해 보자
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@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 hongjun"))
.andDo(print());
}
}
SpringBootTest의 WebEnviroment를 RANDOM_PORT로 지정하여 실제 servlet를 이용한 테스트를 진행해 보자.
package com.hongjun423.springinit.sample;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class SampleControllerTest {
@Autowired
TestRestTemplate testRestTemplate;
@MockBean
SampleService mockSampleService;
@Test
public void hello() {
when(mockSampleService.getName()).thenReturn("hongjun");
String result = testRestTemplate.getForObject("/hello", String.class);
assertThat(result).isEqualTo("hello hongjun");
}
}
링크
해당 포스팅은 백기선님의 강의를 보고 작성하였습니다.
반응형
'Java & 스프링 > 스프링부트 톺아보기' 카테고리의 다른 글
[스프링 부트 ] Nginx 와 함께 배포 하기(2) (1) | 2019.10.15 |
---|---|
[스프링 부트 ] Nginx 와 함께 배포 하기(1) (0) | 2019.10.13 |
[스프링 부트] 로깅 - Log4j 사용 하기 (0) | 2019.10.07 |
[스프링 부트] 로깅 - Logback 커스텀 설정 파일 사용 하기 (0) | 2019.10.07 |
[스프링 부트] 로깅 (0) | 2019.10.07 |
댓글