[SpringBoot] OutputCaputre 테스트 유틸리티

2022. 11. 6. 16:21JAVA/Spring

OutputCapture 테스트 유틸리티

OutputCaputre 테스트 유틸리티는 스프링부트가 제공하는 유틸리티로써 로그 및 콘솔에 출력되는 문자열을 캡처하는 유틸리티입니다.

 

OutputCapture 예제

1. 컨트롤러 및 서비스 정의

@RestController
public class SampleController {
    Logger logger = LoggerFactory.getLogger(SampleController.class);

    @Autowired
    private SampleService sampleService;

    @GetMapping("/hello")
    public String hello(){
        logger.info("kim yonghwan");
        return "hello " + sampleService.getName();
    }
}
  • url로 hello로 접근시 "kim yonghwan" 문자열을 로그로 남김
@Service
public class SampleService {
    public String getName() {
        return "yonghwan";
    }
}

 

2. 테스트코드 작성

@WebMvcTest(SampleController.class)
@ExtendWith(OutputCaptureExtension.class)
public class SampleControllerOutputCaptureTest {
    @MockBean
    SampleService mockSampleService;

    @Autowired
    MockMvc mockMvc;

    @Test
    public void testHello(CapturedOutput output) throws Exception {
        when(mockSampleService.getName()).thenReturn("yonghwan");

        mockMvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string("hello yonghwan"))
                .andDo(print());

        assertThat(output.toString())
                .contains("kim yonghwan");
    }
}
  • 테스트 환경 : Junit5

 

References

source code :https://github.com/yonghwankim-dev/springboot_study/blob/main/springboot_utilization/src/test/java/kr/yh/spring_test/SampleControllerOutputCaptureTest.java
[인프런] 스프링 부트 개념과 활용