spring-boot - 单元测试 - Wiremock 验证失败并出现连接错误

标签 spring-boot junit kotlin wiremock

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

我的测试文件:

@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: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused)



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

最佳答案

您需要使用 wireMockServer.verify() 而不是 WireMock.verify() 之类的东西在您的特定服务器上执行验证调用。

关于spring-boot - 单元测试 - Wiremock 验证失败并出现连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54900364/

相关文章:

spring-boot - Spring Boot应用程序中如何在Java中为Redis Cache设置硬编码 key ?

java - 大量单元测试导致卡住并导致 Binder Transaction 失败

java - 是否可以在 jUnit 中将参数化测试与非参数化测试结合起来?

java - onActivityResult() 未在新的嵌套 fragment API 中调用

android - Recyclerview 不保留我的滚动位置

android - 为什么开发人员不直接将参数传递给 setOnCheckedChangeListener

java - 有没有办法防止 bean 被 Spring Boot 覆盖?

gradle - Spring Boot Gradle 插件 - 多模块 fat jar

java - Spring Security PermitAll() 与排除 url 不匹配

安卓 : instumentation testing for app widgets