我正在尝试编写一个集成测试,以证明如果连接服务器的尝试过慢,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
模拟一个慢速的服务器/连接呢?