새소식

반응형
Spring/Test

[SpringTest] Reactive API WebMvcTest 작성(Mono, Flux)

  • -
반응형

Servlet을 사용한 Web Server를 구동 중이지만, 가끔 WebClient를 이용한 호출을 하는 경우도 있다.

이러한 경우에 WebMvcTest를 이용하여 어떻게 controller layer의 테스트 코드를 작성하는지 정리해 보자.

 

아래 코드는 reactive를 이용한 응답이 아닌 경우 일반적으로 사용하는 코드이다

    @Test
    void test() throws Exception {
        BDDMockito.willThrow(new TestException())
                  .given(testService).addtt(any());
        TestParam param = createParam();

        this.mockMvc.perform(RestDocumentationRequestBuilders.post("/test/add")
                                                             .content(objectMapper.writeValueAsString(param))
                                                             .contentType(MediaType.APPLICATION_JSON))
                    .andExpect(status().is2xxSuccessful())
                    .andDo(document("test/add-failed",
                                    relaxedRequestFields()));
    }

 

우선 RequestResultMatchers.asyncStarted()를 이용해 비동기호출이 이루어졌는지 확인을 한다

다음으로 MockMvcRequestBuilders.asyncDispatch()를 이용해  비동기 호출의 응답을 꺼내온다

import static org.mockito.ArgumentMatchers.any;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.payload.PayloadDocumentation.relaxedRequestFields;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(controllers = TestController.class)
@ExtendWith({RestDocumentationExtension.class})
@AutoConfigureRestDocs
class TestControllerTest {

    @MockBean
    TestService testService;
    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @Test
    void test() throws Exception {
        BDDMockito.given(testService.test(any()))
                  .willReturn(Mono.just(new TestResult("ace")));
        Param param = createParam();

        MvcResult mvcResult = this.mockMvc.perform(RestDocumentationRequestBuilders.post("/test/add")
                                                                                   .content(objectMapper.writeValueAsString(param))
                                                                                   .contentType(MediaType.APPLICATION_JSON))
                                          .andExpect(request().asyncStarted())
                                          .andReturn();

        mockMvc.perform(asyncDispatch(mvcResult))
               .andExpect(status().is2xxSuccessful())
               .andDo(document("test/add", relaxedRequestFields()));
    }
}

 

asyncStarted(), asyncDispatch()  등의 기능을 활용해 비동기 호출의 응답을 검증하고 꺼낼 수 있는 기능을 활용하는 것이다

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.