Spring boot 单元测试-Wiremock验证失败,连接错误

Spring boot 单元测试-Wiremock验证失败,连接错误,spring-boot,junit,kotlin,wiremock,Spring Boot,Junit,Kotlin,Wiremock,我正在测试一个spring启动应用程序,并使用wiremock存根来模拟外部API。在一个测试用例中,我想确保我的存根只被调用一次,但由于连接错误而失败 我的测试文件: @SpringBootTest @AutoConfigureWebTestClient @ActiveProfiles("test") class ControllerTest { @Autowired private lateinit var webClient: WebTestClient pri

我正在测试一个spring启动应用程序,并使用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:连接到本地主机:8080[localhost/127.0.0.1,localhost/0:0:0:0:0:1]失败:连接被拒绝(连接被拒绝)


请告诉我哪里做错了。提前感谢。

您需要使用类似于
wireMockServer.verify()
而不是
WireMock.verify()
的工具在特定服务器上执行验证调用。看起来您模拟的端口不正确。WireMock使用8081,而错误报告大约8080。spring引导应用程序使用8080端口。如果我删除WireMock.verify部分,则测试通过。