单元测试-Wiremock验证失败并出现连接错误 [英] Unit Testing - Wiremock verify failing with connection error
问题描述
我正在测试一个Spring-boot应用程序,并使用Wiremock存根模拟外部API.在一个测试案例中,我想确保我的存根仅被调用一次,但是由于连接错误而失败.
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.
我的测试文件:
@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:连接到localhost:8080 [localhost/127.0.0.1,localhost/0:0:0:0:0:0:0:1]失败:连接被拒绝(连接被拒绝)
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.
推荐答案
您需要使用诸如wireMockServer.verify()
而不是WireMock.verify()
之类的东西在特定服务器上执行验证调用.
You need to perform the verify call on your specific server with something like wireMockServer.verify()
instead of WireMock.verify()
.
这篇关于单元测试-Wiremock验证失败并出现连接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!