Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing - Wiremock verify failing with connection error

I'm testing a spring-boot application and using wiremock stubs to mock external API. In one test case I want to make sure that my stub gets called exactly once but it's failing with connection error.

My Test File:

@SpringBootTest
@AutoConfigureWebTestClient
@ActiveProfiles("test")
class ControllerTest {

    @Autowired
    private lateinit var webClient: WebTestClient

    private lateinit var wireMockServer: WireMockServer

    @BeforeEach
    fun setup() {
        wireMockServer = WireMockServer(8081)
        wireMockServer.start()
        setupStub()
    }

    @AfterEach
    fun teardown() {
        wireMockServer.stop()
    }

    // Stub for external API
    private fun setupStub() {
        wireMockServer.stubFor(
        WireMock.delete(WireMock.urlEqualTo("/externalApiUrl"))
            .willReturn(
                WireMock.aResponse()
                    .withHeader("Content-Type", "application/json")
                    .withStatus(204)
                    .withBodyFile("file.json")
            )
    )
    }

    @Test
    fun test_1() {

        val email = "some-email"
        val Id = 123

        webClient.post()
        .uri { builder ->
            builder.path("/applicationUrl")
                .queryParam("email", email)
                .queryParam("id", Id)
                .build()
        }
        .exchange()
        .expectStatus().isOk

        WireMock.verify(exactly(1), WireMock.deleteRequestedFor(WireMock.urlEqualTo("/externalApiUrl")))
}

When I run this test I'm getting the following error:

org.apache.http.conn.HttpHostConnectException: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused)

Please let me know where I'm doing wrong. Thanks in advance.

like image 923
Avv Avatar asked Dec 08 '22 12:12

Avv


1 Answers

You need to perform the verify call on your specific server with something like wireMockServer.verify() instead of WireMock.verify().

like image 168
Henrik Hermansson Avatar answered Mar 08 '23 15:03

Henrik Hermansson