MockServer throws "Connection refused" while SpringBootTest

Viewed 1002

I just can't get the org.mock-server running. It gives me:

org.mockserver.client.netty.SocketConnectionException: Unable to connect to socket localhost/127.0.0.1:443

Here is the code of my test case:

private ClientAndServer mockServer;

@BeforeClass
public void startServer() {
    mockServer = startClientAndServer(1080);
}

@Test
void downloadByUserShouldRetry() {
    // given
    new MockServerClient("localhost", 443)
        .when(
            request()
                .withSecure(true)
                .withMethod("GET")
                .withPath("myUrl")
                .withHeader("Authorization", "Bearer " + adminAccessToken),
                exactly(1)
            )
            .respond(
                response()
                    .withStatusCode(401)
                    .withHeaders(
                        new Header("Content-Type", "application/json; charset=utf-8"),
                        new Header("Cache-Control", "public, max-age=86400")
                    )
                    .withBody("{ message: 'incorrect username and password combination' }")
                    .withDelay(TimeUnit.SECONDS,1)
            );
1 Answers

It seems like I have stumbled on a similar issue. I had multiple integration test using a single MockServer static instance.

I found the following answer on this Github issue which did the trick for me:

        mockServer.stop();
        while (!mockServer.hasStopped(3,100L, TimeUnit.MILLISECONDS)){}

Basically you're waiting for the server for stopping completely before moving on to the next test. That did the trick for me quite nicely.

Related