WebTestClient with MockWebServer hangs

2k Views Asked by At

I have a spring boot application that exposes a rest api using "spring-boot-starter-webflux". My application calls other rest services when one of my endpoint is called.

I'm trying to make an integration test using WebTestClient to mimic the client calling me and MockWebServer to mimic the external rest service I call.

I'm also overriding a spring configuration to use a webclient that "points" to the MockWebServer in my application.

I see that, when I launch the test, my server starts, and the MockWebServer starts, but when I call my endpoint it seems that the MockWebServer is "stuck" and is not responding.

The test, moreover, ends with "java.lang.IllegalStateException: Timeout on blocking read for 5000 MILLISECONDS from the WebTestClient.

@SpringBootTest(webEnvironment = RANDOM_PORT,
                properties = { "spring.main.allow-bean-definition-overriding=true" })
class ApplicationIT {
    static MockWebServer remoteServer = new MockWebServer();

    @BeforeAll
    static void setUp() throws Throwable {
        remoteServer.start();
    }

    @AfterAll
    static void tearDown() throws Throwable {
        remoteServer.shutdown();
    }

    @Test
    void test(@Autowired WebTestClient client) {
        remoteServer.enqueue(new MockResponse().setBody("..."));

        client.get()
              .uri("...")
              .exchange()
              .expectStatus()
              .isOk();
    }

    @TestConfiguration
    static class SpringConfiguration {
        WebClient remoteClient() {
            return WebClient.builder()
                            .baseUrl("http://" + remoteServer.getHostName() + ":" + remoteServer.getPort())
                            .build();
        }
    }
}
1

There are 1 best solutions below

0
On

Are you sure that your integration tests uses the WebClient bean you specified inside your @TestConfiguration?

It seems there is an @Bean annotation missing:

@TestConfiguration
static class SpringConfiguration {

    @Bean
    WebClient remoteClient() {
        return WebClient.builder()
                        .baseUrl("http://" + remoteServer.getHostName() + ":" + remoteServer.getPort())
                        .build();
    }
}