【发布时间】:2012-10-28 07:42:36
【问题描述】:
我正在使用套接字服务器并尝试根据测试驱动开发模式工作。
有一个套接字创建方法的工作测试,但我的测试挂起,因为我有一个 ManualResetEvent.WaitOne() 以便我的套接字在创建另一个连接之前等待连接。
这是要测试的代码块:
ManualResetEvent allDone = new ManualResetEvent(false);
public void StartListening()
{
allDone.Reset();
//Inform on the console that the socket is ready
Console.WriteLine("Waiting for a connection...");
/* Waits for a connection and accepts it. AcceptCallback is called and the actual
* socket passed as AsyncResult
*/
listener.BeginAcceptTcpClient(
new AsyncCallback(AcceptCallback),
listener);
allDone.WaitOne();
}
这是挂在“networkChannel.StartListening();”处的测试方法
[TestMethod]
public void NetworkChannel_IsAcceptingConnectionsAsynchronously()
{
ITcpClient client = MockRepository.GenerateMock<ITcpClient>();
ITcpListener listener = MockRepository.GenerateMock<ITcpListener>();
IAsyncResult asyncResult = MockRepository.GenerateMock<IAsyncResult>();
listener.Expect(x => x.BeginAcceptTcpClient(null, null)).IgnoreArguments().Return(asyncResult);
listener.Expect(x => x.EndAcceptTcpClient(asyncResult)).Return(client);
NetworkChannel networkChannel = new NetworkChannel(listener);
networkChannel.StartListening();
//Some more work... fake callback etc., verfify expectations,...
}
如果我评论所有的手动重置事件,测试通过就好了,但这不是解决方案,因为服务器会不断尝试创建重复的套接字;-)
对我有什么提示吗?将不胜感激!
问候, 马丁
【问题讨论】:
标签: c# .net unit-testing sockets tdd