使用MockWebServer模拟响应时,Mono.flatMap无法正常工作

时间:2018-11-19 12:15:12

标签: java spring spring-webflux reactor mockwebserver

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

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

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

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

以下是用于模拟HTTP响应的代码段

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

我认为造成这种现象的原因是由于MockWebServer在内部创建模拟的方式引起的。我在这里想念什么?

1 个答案:

答案 0 :(得分:0)

我使用MockWebServer和webClient,这似乎很好。也许您可以发布更多详细信息。

这是我的设置的摘要-请注意,这不是弹簧测试

@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的包装器