Wiremock-有时它抛出";软件导致的连接中止:recv失败"; [英] Wiremock - sometimes it throws "Software caused connection abort: recv failed"
本文介绍了Wiremock-有时它抛出";软件导致的连接中止:recv失败";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在使用Spring和Wiremock进行集成测试时,我遇到了一个非常奇怪的情况:突然,一个特定的测试开始间歇性地失败。下面的错误片段:
org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:10314/my/endpoint": Software caused connection abort: recv failed; nested exception is java.net.SocketException: Software caused connection abort: recv failed
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:785) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:468) ~[spring-web-5.3.7.jar:5.3.7]
... more logs here ...
上下文如下: 我添加了一个使用wiremock来存根响应的新测试:
wireMockServer.stubFor(WireMock.post("/my/endpoint")
.withRequestBody(containing(aJsonRequestBodyHere))
.willReturn(aResponse()
.withBody(aJsonResponseHere)
.withStatus(HttpStatus.OK.value())
.withHeader(HttpHeader.CONTENT_TYPE.toString(), CONTENT_TYPE_APPLICATION_JSON)));
对此存根终结点的调用如下:
given()
.when()
.get("my/endpoint")
.then()
.body(containsString(theExpectedJsonResponse)))
.statusCode(200);
奇怪的部分:
- 相同的测试在我的本地计算机上运行时没有任何问题-如果单独运行
- 在我的计算机上运行所有测试时,有时相同的测试失败,有时不失败
- 每次仅此测试失败;没有其他测试失败
- 在Jenkins上运行测试时,100%失败
推荐答案
对此稍加挖掘后,我发现this和this两篇文章几乎百分之百描述了我的情况。
根本原因似乎是测试执行得太快-可能是那些没有做太多事情的测试-Wiremock没有时间为下一次测试正确设置。
我已经通过在测试开始时添加Thread.sleep(2000)
来测试这个假设,然后多次运行所有测试-所有测试都通过了,没有问题。
解决方案在the first article中介绍:注册将截获所有响应的Transformer类,并向其添加Connection=close
标头。
更多细节:我添加了一个Transformer
类,该类扩展了ResponseDefinitionTransformer
,并在每个响应上添加了Connection
头。然后,我创建了@Configuration
带注释的类,并注册了Transformer
Transformer类(取自the first article):
public class NoKeepAliveTransformer extends ResponseDefinitionTransformer {
@Override
public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, FileSource files, Parameters parameters) {
return ResponseDefinitionBuilder.like(responseDefinition)
.withHeader(HttpHeaders.CONNECTION, "close")
.build();
}
@Override
public String getName() {
return "keep-alive-disabler";
}
}
配置类:
@Configuration
public class WiremockConfiguration {
@Bean
WireMockConfigurationCustomizer optionsCustomizer() {
return options -> options.extensions(NoKeepAliveTransformer.class);
}
}
这篇关于Wiremock-有时它抛出";软件导致的连接中止:recv失败";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文