Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MockServer throws "Connection refused" while SpringBootTest

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)
            );
like image 722
k-wasilewski Avatar asked Jan 18 '26 20:01

k-wasilewski


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.

like image 61
avi.elkharrat Avatar answered Jan 21 '26 13:01

avi.elkharrat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!