How configure WireMock to use https (and a random

2019-06-08 02:46发布

问题:

I tried to set wiremock to run https on a random port:

@Rule
public WireMockRule wireMockServer = new WireMockRule(
    WireMockConfiguration.wireMockConfig().dynamicPort().dynamicHttpsPort()
);

but when I use this and I call wireMockServer.httpsPort() I get the exception:

java.lang.IllegalStateException: Not listening on HTTPS port. Either HTTPS is not enabled or the WireMock server is stopped.
    at com.google.common.base.Preconditions.checkState(Preconditions.java:150)
    at com.github.tomakehurst.wiremock.WireMockServer.httpsPort(WireMockServer.java:184)

How do i set WireMock to use https?

NOTE: I'm using version 2.14.0

回答1:

I used a WireMockRules class and had my test classes inherit from it

import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

public class WiremockRules {
    @Rule
    public WireMockRule wireMockRule = new WireMockRule(
        wireMockConfig().dynamicPort().dynamicHttpsPort()
    );
}

and my WiremockTest.java

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest()
public class WiremockTest extends WiremockRules {

    private String url;

    @Before
    public void setup() {
        url = baseUrl + Integer.toString(wireMockRule.port()) + "/v1/test";

        stubFor(
            get(urlEqualTo(url))
                .willReturn(
                    aResponse()
                        .withStatus(HttpStatus.OK.value())
                )
        );
    }
}