Test with MockWebServer never finishes

Viewed 421

I have a class which implements CommandLineRunner and in its run method a webClient makes a request and does some processing with the response, including a method that I want to verify in a test:

@RequiredArgsConstructor
public class WowGreatClass implements CommandLineRunner {
    private final WebClient webClient;

    @Override
    public void run(String... args) {
        webClient.get()
            .uri("/foo")
            .retrieve()
            .bodyToMono(PairsResponseDto.class)
            .flatMap(response -> Flux.fromIterable(response.getResult()))
            .collectList()
            .map(this::methodToTest)
            //...
        ).block(); 
    }
}

So I am using a MockWebServer in the test like so:

@ExtendWith(MockitoExtension.class)
public class WowGreatTest {

    MockWebServer mockServer = new MockWebServer();

    @Spy
    WowGreatClass greatClass = new WowGreatClass(WebClient.create(mockServer.url("/").toString()));

    @Captor
    ArgumentCaptor<String> captor;

    @Test
    public void testTheThing() {
        mockServer.enqueue(
            new MockResponse()
                .setResponseCode(200)
                .addHeader("Content-Type", "application/json")
                .setBody("something really interesting"));

        greatClass.run();
        verify(greatClass).methodToTest(captor.capture());
    }
}

The MockWebServer does what it should during the test, the issue is that after the initial request it seems to just hang forever waiting for more. The run() method never finishes and the verify() call is never reached. Am I missing something obvious here, or what's wrong?

1 Answers

MockServer.url("/") return something like this: http://kubernetes.docker.internal:49954/ so when you pass this to WebClient in run method your url looks like: http://kubernetes.docker.internal:49954//foo with // beacause of .uri("/foo") in your WebClient builder.

Instead of mockServer.url("/").toString() just use "http://localhost:" + mockServer.getPort()

Related