模拟org.springframework.web.reactive.function.client.WebClient.ResponseSpec#onStatus输入参数

时间:2019-12-30 12:02:10

标签: java mockito webclient

考虑以下代码:

    public Mono<Void> doStuff() {

        return this.requestStuff()
            .onStatus(HttpStatus::is5xxServerError,
                    clientResponse -> {
                    aMethodIWouldLikeToTest(clientResponse);
                    return Mono.error(new MyCustomException("First error I would like to test"));
                    })
            .onStatus(HttpStatus::is4xxClientError,
                    clientResponse -> {
                    aMethodIWouldLikeToTest(clientResponse);
                    return Mono.error(new MyCustomException("Second error I would like to test"));
                    })
            .bodyToMono(String.class)
            .flatMap(x -> anotherMethodIManagedToTest(x)))

    }

我的首要目标是测试使用以下方法实现的 otherMethodIManagedToTest(x)

    import org.springframework.web.reactive.function.client.WebClient;

    ...

    @Mock
    private WebClient.ResponseSpec responseSpec;

    private String desiredInputParam = "There is another black spot on the sun today!";

    ...

    @Test
    public void allGood_anotherMethodIManagedToTest_success {

        ...

        ClassUnderTest classUnderTest = new classUnderTest()
        ClassUnderTest classUnderTestSpy = spy(classUnderTestSpy);
        doReturn(responseSpec).when(classUnderTestSpy).requestStuff();

        when(responseSpec.onStatus(any(), any())).thenReturn(responseSpec);
        when(responseSpec.bodyToMono(String.class)).thenReturn(Mono.just(desiredInputParam));

        Mono<Void> result = classUnderTestSpy.doStuff();

        // Bunch of assertions for anotherMethodIManagedToTest(String desiredInputParam) performed with success ...

    }

现在,我想创建其他测试来测试5xxServerError事件和4xxClientError事件,但是我很难确定如何做到:

  • 模拟 HttpStatus :: is5xxServerError
  • 的响应
  • 模拟 HttpStatus :: is4xxServerError
  • 的响应
  • 模拟clientResponse以便测试 aMethodIWouldLikeToTest(org.springframework.web.reactive.function.client.ClientResponse clientResponse)

关于如何执行这些操作的任何建议?

请注意,我不能真正使用任何PowerMock替代方法(如果这是实现我的目标的唯一途径,请继续关注),所有使用标准Mockito的答案都是首选。

1 个答案:

答案 0 :(得分:0)

我认为我的问题的答案是 Mockito不是测试这种事情的正确工具。使用Wiremock似乎很方便

当我主要使用以下库进行测试时:

  • 导入com.github.tomakehurst.wiremock.client.WireMock;
  • 导入org.springframework.test.context.junit4.SpringRunner;
  • 导入org.springframework.boot.test.context.SpringBootTest;
  • 导入org.springframework.test.web.reactive.server.WebTestClient;

我设法完成了工作。

如果您遇到类似的问题,建议您看一下https://www.sudoinit5.com/post/spring-boot-testing-consumer/,所提供的示例与我为完成测试所做的类似。

但是,如果有人知道用Mockito解决问题的方法,我仍然很感兴趣。

相关问题