본문 바로가기
Spring Boot

Spring boot 단위 테스트

by 상국이 2022. 2. 20.
728x90

단위 테스트 (Slice Test)

 > 레이어별로 잘라서 테스트하고 싶은 경우

 

사용 방법 (이전의 예제 사용)

참고 : https://developing-countries.tistory.com/57 의 3번 예제

 

@WebMvcTest 

  > web관련 Bean만 생성 > Service들을 MockBean으로 생성해줘야함

  ex) @Controller, @ControllerAdvice, @JsonComponent

@RunWith(SpringRunner.class)
@WebMvcTest(SampleController.class)
class SampleControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    SampleService mockSampleService;

    @Test
    public void hello() throws Exception {
        when(mockSampleService.getName()).thenReturn("SANG_GUK");

        mockMvc.perform(get("/hello"))              //get() -> org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
                .andExpect(content().string("hello SANG_GUK"));         
        //content() ->org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
    }
}
728x90

'Spring Boot' 카테고리의 다른 글

ViewResolver  (0) 2022.02.27
HttpMessageConverters  (0) 2022.02.20
Spring boot 통합 Test  (0) 2022.02.20
Logging  (0) 2022.02.20
프로파일  (0) 2022.02.20

댓글