jeudi 17 septembre 2020

How to test WireMockServer in JUnit5?

I am trying to write a mini-library for testing to mock common external services such as E-mail, SFTP, Buckets, HTTP APIs.

At the moment, I got stuck on WireMockServer. In WireMock docs it states that I can create both server and client to verify API calls.

I wrote the class:

public class WireMockTestServer {

    private final WireMockServer server;

    public WireMockTestServer(String address, MappingBuilder mappingBuilder) {
        server = new WireMockServer(wireMockConfig().dynamicPort().dynamicHttpsPort());
    }

    public WireMockTestServer(int httpPort, int httpsPort, String address, MappingBuilder mappingBuilder) {
        server = setup(
                new WireMockServer(wireMockConfig().port(httpPort).httpsPort(httpsPort).bindAddress(address)),
                mappingBuilder
        );
    }

    private WireMockServer setup(WireMockServer server, MappingBuilder mappingBuilder) {
        server.stubFor(mappingBuilder);
        return server;
    }

    public void start() {
        server.start();
    }

    public void stop() {
        server.stop();
    }
}

which I can path endpoint declaration and redirect my services toward it.

When I am trying to test it:

public class WireMockTestServerTest {

    @Test
    public void testSetup() throws Exception {
        MappingBuilder mappingBuilder = get(urlEqualTo("/health"))
                .willReturn(aResponse().withHeader("Content-Type", "application/json")
                        .withStatus(200));
        WireMockTestServer server = new WireMockTestServer(8888, 9988, "127.0.0.1", mappingBuilder);
        server.start();


        // This line should fail
        verify(getRequestedFor(urlEqualTo("/health")).withHeader("Content-Type", equalTo("text/xml")));
        server.stop();
    }

}

The test fails. The issue is, it fails not because of an assertion but because it starts on a wrong port 8080 which is occupied by other processes.

How can I start WireMockServer on another port and test it with JUnit 5?

I am using Java 8, Maven, Spring Boot.

Aucun commentaire:

Enregistrer un commentaire