7

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?

summerbulb
  • 5,709
  • 8
  • 37
  • 83

1 Answers1

4

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

summerbulb
  • 5,709
  • 8
  • 37
  • 83
  • I'm having the same issue as described above. However, [this](https://stackoverflow.com/a/34379236/7435524) didn't resolve my problem. It's still trying to spin the server on the same port 8080. Although, the one specified is 8888. Anyone has an idea. My code is literally the same as in the [Getting Started](http://wiremock.org/docs/getting-started/) guide. – KareemJ Aug 25 '20 at 15:04
  • Like @KareemJeiroudi I have the same problem and it doesn't resolve this error. – lecogiteur Apr 13 '22 at 09:54