Mockitoを用いたSpring WebFluxのテストコード

Dev/Java/Spring Boot
Spring
Spring Boot
Spring WebFlux

更新日時 : 2021/01/17 12:22
投稿日時 : 2021/01/17 12:22

JUnit5でMockitoを利用したテストコードを書くときのメモ。
@ExtendWith(MockitoExtension.class)がクラスアノテーションに必要。
あとは今までのMockitoの設定と変わらず。
WebFluxライブラリを用いるときのリクエストのテストはorg.springframework.test.web.reactive.server.WebTestClientを用いる。

@ExtendWith(MockitoExtension.class)
public class TogglWrapperHandlerTest {
    WebTestClient client;

    @Mock
    private TogglWrapperService togglWrapperService;
    @Mock
    private TogglWrapperVerifier togglWrapperVerifier;
    @Mock
    private IftttService iftttService;

    @BeforeEach
    public void setUp() {
        TogglWrapperHandler togglWrapperHandler =
                new TogglWrapperHandler(togglWrapperService, togglWrapperVerifier, iftttService);
        RouterFunction routerFunction = togglWrapperHandler.routes();
        when(togglWrapperService.start("description", 0))
                .thenReturn(Mono.just(ConnectorResponseBody.builder()
                        .message("success").body(new TogglTimeEntryResponseBody()).build()));
        when(togglWrapperService.getTimeEntryFromPastRecord("description", 0))
                .thenReturn(Mono.just(new TogglTimeEntry()));
        client = WebTestClient.bindToRouterFunction(routerFunction).configureClient().build();
    }

    @Test
    public void startSelectable() {
        client
                .post()
                .uri("/toggl/start")
                .accept(MediaType.APPLICATION_JSON)
                .body(Mono.just(new TogglWrapperEntryRequest("description", 0, 0, "test-key")), TogglWrapperEntryRequest.class)
                .exchange()
                .expectStatus()
                .isOk();
    }
}