【问题标题】:The Mono.flatMap is not working while mocking the response using MockWebServerMono.flatMap 在使用 MockWebServer 模拟响应时不起作用
【发布时间】:2018-11-19 12:15:12
【问题描述】:

使用 WebClient 进行 HTTP 调用,从 Mono 输出中我想做一些逻辑,为此我使用 flatMap 方法。

        Mono<Response> authResponseMono = webClient.post().syncBody(requestBody)
            .retrieve()
            .bodyToMono(Response.class);

        return authResponseMono.flatMap(authResponse -> {
        //code removed for brevity
        });

使用 OkHttp MockWebServer 库来模拟响应并对功能进行单元测试。 flatMap 方法在使用 MockWebServer 时没有被调用,但是,在实际调用中一切正常。

下面是用来模拟HTTP响应的sn-p

server.enqueue(mockResponse); //server is instance of MockWebServer
Optional<Response> optionalResponse = authClientService.verifyToken().block(); //verifyToken returns authResponseMono

我认为这种行为的原因是 MockWebServer 在内部创建模拟的方式。我在这里错过了什么?

【问题讨论】:

    标签: java spring spring-webflux reactor mockwebserver


    【解决方案1】:

    我使用 MockWebServer 和 webClient 似乎还不错。也许您可以发布更多详细信息。

    这是我的设置的 sn-p - 注意这不是弹簧测试

    @RunWith(MockitoJUnitRunner.class)
    public class AccountDetailsRetrievalTest {
    
        private static final String ACCOUNT_DETAILS_PATH = "/AccountDetailsPath";
        private MockWebServer server;
    
        private WebClient webClient;
    
        private AccountDetailsRetrieval accountDetailsRetrieval;
    
        @Before
        public void setup() {
            this.server = new MockWebServer();
            this.webClient = WebClient.create(this.server.url(ACCOUNT_DETAILS_PATH).toString());
            accountDetailsRetrieval = new AccountDetailsRetrieval(this.webClient, ACCOUNT_DETAILS_PATH, 300);
        }
    
        @After
        public void shutdown() throws Exception {
            this.server.shutdown();
        }
    
    @Test
    public void nameHasBeenChanged() {
        String content = "{\"bar\":\"bar1\",\"foo\":\"foo1\"}";
        MockResponse response1 = new MockResponse()
                .setHeader("Content-Type", "application/json")
                .setBody(content);
        this.server.enqueue(response1);
    
        StepVerifier.create(accountDetailsRetrieval.getAccountData(new AccountDetails("001", "ABC")))
                .assertNext(response -> {
                    assertThat(response).isNotNull();
                    assertThat(response.getHttpStatus()).isEqualByComparingTo(HttpStatus.OK);
                    assertThat(response.data().get("bar")).isEqualTo("bar1");
                    assertThat(response.data().get("foo")).isEqualTo("foo1");
                })
                .verifyComplete();
    }
    

    这里的响应只是 JsonNode 的一个包装器

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 2021-05-26
      • 2014-09-17
      • 2018-03-30
      • 1970-01-01
      • 2013-09-16
      相关资源
      最近更新 更多