サーバーへの接続試行が遅すぎる場合に 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
andを使用して遅いサーバー/接続を偽造する方法はありますSocket
か?