0

我需要创建一个集成测试来演示成功地将 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());
    }

但是,这不像上面的评论那样工作。有人看到我在这里缺少什么吗?

4

1 回答 1

0

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

于 2011-02-02T19:23:23.573 回答