【发布时间】:2013-11-28 09:33:32
【问题描述】:
我已经为我们在工作场所开发的系统的特定需求编写了一个事件驱动的 tcp 服务器。我还为此编写了单元测试。
在每个测试中,我都使用标准 C# TcpListener 和 TcpClient 连接到我的库。我正在将特定的数据位写入其中,然后检查测试代码是否触发了适当的事件。
问题是——这是一场比赛!我的意思是,有时当我向 TcpClient 写入数据时,可能会立即触发事件,有时可能需要 100 毫秒,有时如果计算机速度很慢(或连接速度很慢),则需要更多时间。
说了这么多,我们来画一个简单的测试(顺便说一下我用的是NUnit):
[Test]
public void TestEventA()
{
bool eventFired = false;
//my server would listen on 127.0.0.1:9090
MyTcpServer serv = new MyTcpServer("127.0.0.1", 9090);
serv.OnA += new AEventHandler((object sender, AEventArgs args) =>
{
eventFired = true;
});
//imitating a remote client connecting
TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 9090);
//remote client is sending data
client.Getstream().Write(/*you know the drill here*/);
//give the connection and server time to react
System.Threading.Sleep(100);
Assert.IsTrue(eventFired);
}
所以这只是一个简单的测试示例。问题是 - 它每次都在我的本地 PC 上通过,但在我们的构建服务器上它是完全随机的。现在我 100% 确定这是因为当我们到达断言时事件还没有被触发。问题是,我不知道如何正确设计测试以避免这种竞争条件。
我相信你们中的许多人都做过类似的事情(可能不是使用 TCP,而是测试事件驱动的东西,当我们不知道事件触发需要多长时间等时),所以我很想学习你的经历。
谢谢。
【问题讨论】:
标签: c# unit-testing events tcp nunit