【发布时间】:2012-07-16 09:17:14
【问题描述】:
我正在尝试编写一个集成测试来证明如果连接到服务器的尝试太慢,TCP 客户端将正确超时。我有一个FakeServer 类,它打开一个Socket 并监听传入的连接:
public sealed class FakeServer : IDisposable
{
...
public TimeSpan ConnectDelay
{
get; set;
}
public void Start()
{
this.CreateSocket();
this.socket.Listen(int.MaxValue);
this.socket.BeginAccept(this.OnSocketAccepted, null);
}
private void CreateSocket()
{
var ip = new IPAddress(new byte[] { 0, 0, 0, 0 });
var endPoint = new IPEndPoint(ip, Port);
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.socket.Bind(endPoint);
}
private void OnSocketAccepted(IAsyncResult asyncResult)
{
Thread.Sleep(this.connectDelay);
this.clientSocket = this.socket.EndAccept(asyncResult);
}
}
请注意我尝试通过调用Thread.Sleep() 来延迟连接成功。不幸的是,这不起作用:
[Fact]
public void tcp_client_test()
{
this.fakeServer.ConnectDelay = TimeSpan.FromSeconds(20);
var tcpClient = new TcpClient();
tcpClient.Connect("localhost", FakeServer.Port);
}
在上面的测试中,对tcpClient.Connect() 的调用立即成功,甚至在服务器端OnSocketAccepted 方法被调用之前。我查看了 API,但看不到任何明显的方法可以注入一些必须在来自客户端的连接建立之前完成的服务器端逻辑。
我有什么方法可以使用TcpClient 和Socket 来伪造慢速服务器/连接?
【问题讨论】:
-
+1 用于实际测试不良/慢速连接,这与其他无知世界不同 :)
-
您可以使用像 NetLimiter 这样的工具来限制连接。可惜不是免费的。
-
这里也有一些通用的解决方案:webmasters.stackexchange.com/questions/861/…
-
我不喜欢网络工具,因为它是作为集成测试运行的。
标签: .net sockets tcp integration-testing