java - 模拟 WebClient post 方法失败

标签 java mocking mockito spring-webflux spring-webclient

我可以找到几个有关模拟 WebClient 对象的问题。但是,当我发布带有正文且具有多个标题值的帖子时,我仍然遇到问题。我只是使用 Mockito。

public Boolean addNote(AlarmModel model) {
        ServiceDTO dto = mapper(model);

        return webClient.post()
                .uri("/service/api/addNotes")
                .headers(getHttpHeaders(dto.getHeader()))
                .accept(MediaType.APPLICATION_JSON)
                .body(Mono.just(dto.getBody()), ServiceBodyDTO.class)
                .retrieve()
                .onStatus(HttpStatus::is5xxServerError, this::handleStatusCodeError)
                .onStatus(HttpStatus::is4xxClientError, this::handleStatusCodeError)
                .bodyToMono(Boolean.class)
                .block();
    }

这就是我 mock post 方法的行为的方式。

        when(webClientMock.post()).thenReturn(requestBodyUriMock);
        when(requestBodyUriMock.uri(anyString())).thenReturn(requestBodyMock);
        
        when(requestHeadersMock.headers(any())).thenReturn(requestHeadersMock);

        when(requestBodyMock.accept(any())).thenReturn(requestBodyMock);
        when(requestBodyMock.contentType(any())).thenReturn(requestBodyMock);
        when(requestBodyMock.bodyValue(any())).thenReturn(requestHeadersMock);
        when(requestHeadersMock.retrieve()).thenReturn(responseMock);
        when(responseMock.bodyToMono(Boolean.class))
                .thenReturn(Mono.just(true));

但是,当我执行这个测试用例时,它在具有 retrieve() 的行处失败,异常是 java.lang.NullPointerException

我在这里错过了什么吗? TIA。

最佳答案

同意 @Martin 的评论,单元测试 Web 客户端的投资返回率非常低。

我会推荐WireMock它为测试 Web 客户端提供了非常好的 API。以下是一些示例

stubFor(post("/service/api/addNotes")
        .withHeader(HttpHeaders.ACCEPT, containing(MediaType.APPLICATION_JSON_VALUE))
        .willReturn(aResponse()
                .withStatus(200)
                .withBody("true")
        )
);

StepVerifier.create(service.addNote(note))
        .expectNextCount(1)
        .verifyComplete();

您可以通过提供不同的 stub 轻松测试正面和负面场景

stubFor(post("/service/api/addNotes")
        .withHeader(HttpHeaders.ACCEPT, containing(MediaType.APPLICATION_JSON_VALUE))
        .willReturn(aResponse()
                .withStatus(500)
        )
);

使用 Scenarios 测试重试逻辑甚至使用 Delays 模拟超时

ps

不确定您为什么使用block但我的例子是使用 StepVerifier并假设 addNote返回Mono<Boolean>

关于java - 模拟 WebClient post 方法失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71356276/

相关文章:

android - 有没有办法在 AsyncTask 的抽象类保护方法中对代码进行单元测试?

unit-testing - NSubstitute:无法模拟与没有相应 setter 的成员变量关联的语法糖 getter 方法

python - 模拟单元测试引发 "stop called on unstarted patcher"错误

python - 单元测试sqlalchemy BinaryExpression

java - 如何使用 Mockito 从自定义属性文件加载值进行 junit 测试?

spring-boot - @WebMvcTest 发现状态 404 且服务返回 null

java - Hadoop 中的 NoClassDefFoundError 错误

java - 是否可以仅从 wsdl 文件创建 Web 服务客户端?

java - 自定义异常类的修饰符 (java)

java - 随机生成的 UUID 有重复项