Search code examples
javaspringspring-bootwiremockwiremock-standalone

How to set wiremock server and stub request based on hostname


I was able to implement the basic setup of wire mock by using:

   public void mock(){
        WireMockServer wireMockServer = new WireMockServer(443)
        wireMockServer.start()
        configureFor("localhost", 443)
        stubFor(post(urlEqualTo("/path/link")).willReturn(aResponse().withBody("hello world")).withStatus(200))
    }

This works well for any resource running on localhost port 8080 like this http://localhost:8080/path/link.

what if I want to mock for a hostname like https://apigeew-uat.company.net/path/link that doesn't have any port specified. How will the port be determined here?

what is configureFor used for?. I understand we specify the port the wiremock server to run but don't quiet understand configure for.


Solution

  • URLs without port numbers are by default on port 80 for HTTP or 443 for HTTPS.

    So if you want to run WireMock on HTTPS without a port number you need to start it with the HTTPS port set to 443:

    WireMockServer wireMockServer = new WireMockServer(wireMockConfig().httpsPort(443));
    

    By default WireMock will present its own self-signed TLS certificate which won't be trusted by your web browser or HTTP clients. Either you'll need to configure these to trust WireMock's cert or provide your own cert as documented here: https://wiremock.org/docs/https/

    Note that *nix systems will require the WireMock process (or the parent Java program in this case) to be run with root privileges to be able to bind to a port number < 1024.