summerbulb
summerbulb

Reputation: 5879

HttpHostConnectException when initializing WireMock HTTP server

I'm trying to test my code that has an underlying GET call to an HTTP server.

I am trying to use WireMock, and base on the "Getting Started" I have the following code:

@Rule
public WireMockRule wireMockRule = 
    new WireMockRule(WireMockConfiguration.wireMockConfig().port(8888)); // No-args constructor defaults to port 8080

@BeforeClass
public static void beforeClass(){
    stubFor(get(urlEqualTo("/Path/Get"))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withBody("[1]")));
}

@Test
public void testGetRanking() throws Exception {
    Fetcher fetcher = new Fetcher("http://localhost:8888",null);
    int rankinganking = fetcher.getRanking("Max");
    Assert.assertEquals(1, ranking);
}

When I run the test, I get the following stack-trace:

wiremock.org.apache.http.conn.HttpHostConnectException: Connect to localhost:8080 [localhost/127.0.0.1] failed: Connection refused
at wiremock.org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:151)
at wiremock.org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
at wiremock.org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
at wiremock.org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
...

The error talks about port 8080, but I configured the port to be 8888. I know that by default WireMock starts with port 8080, so this might be an issue with its internal configuration.

What is the issue here?

Upvotes: 7

Views: 8611

Answers (1)

summerbulb
summerbulb

Reputation: 5879

The problem here is that @BeforeClass executes before @rule. Moving the stubbing into a @Before method or straight into the test solves the problem.

Upvotes: 4

Related Questions