是否可以使用 wiremock 工具模拟连接超时?

Is it possible to simulate connection timeout using wiremock tools?

我知道用withFixedDelay可以模拟SocketTimeoutException,但是ConnectionTimeoutException呢?

结帐 https://github.com/tomakehurst/saboteur 可让您模拟网络问题。或者您可以使用 iptables 自行完成。

是的,可以通过针对 Java API 调用 addDelayBeforeProcessingRequests(300) 或将以下内容发布到 http://<host>:<port>/__admin/socket-delay:

来使用 WireMock 执行此操作

{ "milliseconds": 300 }

(显然用您想要延迟的毫秒数替换 300)

似乎这个问题的答案是“否”,因为 version 2.0.8-beta

Tom(WireMock 的作者)解释了为什么 in this GitHub issue:

It's basically impossible to reliably force connection timeouts in pure Java at the moment.

It used to be the case that you could inject a delay before calling .accept() on the socket, but that stopped working a while back, I guess due to a change in the implementation internals.

My recommendation at the moment would be to use a tool that works at the level of the network stack. iptables ... -j DROP type commands will do the trick, or if you want a level of automation over this you can use tools such as https://github.com/tomakehurst/saboteur or https://github.com/alexei-led/pumba.

他还继续解释说,仅仅停止 WireMock 并不能达到同样的效果:

shutting down WireMock won't have the same effect - when a port is not being listened on, you get a TCP RST (reset) packet back, whereas a connection timeout happens when you get nothing back from the server in the timeout window after your initial SYN packet.

使用WireMock.Net时,也可以添加延迟。

示例:

var server = WireMockServer.Start();

// add a delay of 30 seconds for all requests
server.AddRequestProcessingDelay(TimeSpan.FromSeconds(30));

var server = WireMockServer.Start();
server
  .Given(Request.Create().WithPath("/slow"))
  .RespondWith(
    Responses.Create()
      .WithStatusCode(200)
      .WithBody(@"{ ""msg"": ""Hello I'm a little bit slow!"" }")
      .WithDelay(TimeSpan.FromSeconds(10)
  )
);