【问题标题】:Unit Testing - Wiremock verify failing with connection error单元测试 - Wiremock 验证失败并出现连接错误
【发布时间】:2019-07-20 20:57:44
【问题描述】:

我正在测试一个 spring-boot 应用程序并使用 wiremock 存根来模拟外部 API。在一个测试用例中,我想确保我的存根只被调用一次,但由于连接错误而失败。

我的测试文件:

@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")))
}

当我运行此测试时,我收到以下错误:

org.apache.http.conn.HttpHostConnectException: 连接到 localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] 失败:连接被拒绝(连接被拒绝)

请让我知道我哪里做错了。提前致谢。

【问题讨论】:

  • 看起来你在模拟错误的端口。 WireMock 使用 8081,而错误抱怨 8080。
  • 8080 端口被 spring-boot 应用程序使用。如果我删除 WireMock.verify 部分,则测试通过。

标签: spring-boot junit kotlin wiremock


【解决方案1】:

您需要在特定服务器上执行验证调用,例如 wireMockServer.verify() 而不是 WireMock.verify()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 2014-11-19
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多