2011-02-02 22 views
0

我需要创建一个集成测试,演示如何将UDP数据包成功发送到远程软件。远程软件在测试环境中是不可用的(这是一个传统但仍支持的版本),并且不在我的控制之下,所以我认为我会设置一个测试,至少证明命令按预期发生。阅读this question's answers后,我建立了我的代码如下:UDP算法的集成测试

public void TestRemoteCommand() 
    { 
     //A "strategy picker"; will instantiate a version-specific 
     //implementation, using a UdpClient in this case 
     var communicator = new NotifyCommunicator(IPAddress.Loopback.ToString(), "1.0"); 
     const string message = "REMOTE COMMAND"; 
     const int port = <specific port the actual remote software listens on>; 
     var receivingEndpoint = new IPEndPoint(IPAddress.Loopback, port); 

     //my test listener; will listen on the same port already connected to by 
     //the communicator's UdpClient (set up without sharing) 
     var client = new UdpClient(); 
     client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); 
     client.Client.Bind(receivingEndpoint); 

     //Results in the UDP diagram being sent 
     communicator.SendRemoteCommand(); 

     //This assertion always fails 
     Assert.IsTrue(client.Available > 0); 
     var result = client.Receive(ref receivingEndpoint); 

     Assert.AreEqual(result.Select(b => (char)b).ToArray(), message.ToCharArray()); 
    } 

但是,这是行不通的如上评论。有人看到我在这里失踪了吗?

回答

0

断言发生的方式太快。您正在发送数据,并立即检查要接收的数据。它往往会失败,因为往返客户端和返回的往返时间要比您的程序执行下一行所用的纳秒长。在某处放置一个等待语句,或者创建一个while循环来检查数据,休眠几毫秒,然后再次检查。

+0

原来是它的一部分。我再次抨击它,并发现我在所有的端口上监听,而不是在特定的端口上监听,而这个端口不工作。但是,是的,我还不得不抛出一个快速的Thread.Sleep()语句来确保数据包通过硬件层进入接收存储桶。它实际上运行良好,一次运行一个测试,但在套件中失败。 – KeithS 2011-02-02 20:21:43