【问题标题】:Integration testing of a UDP algorithmUDP算法的集成测试
【发布时间】:2011-02-02 18:40:34
【问题描述】:

我需要创建一个集成测试来演示成功地将 UDP 数据包发送到远程软件。远程软件在测试环境中不可用(它是一个遗留但仍受支持的版本)并且不受我的控制,所以我想我应该设置一个测试,至少证明命令按预期执行。看完this question's answers,我的代码设置如下:

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());
    }

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

【问题讨论】:

    标签: c# udpclient


    【解决方案1】:

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

    【讨论】:

    • 原来是其中的一部分。我又敲了几下,发现我让它监听所有端口而不是特定端口,这不起作用。但是,是的,我还必须输入一个快速的 Thread.Sleep() 语句,以确保数据包通过硬件层进入接收桶。它实际上一次运行一项测试运行良好,但在套件中失败了。
    猜你喜欢
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2011-04-25
    • 1970-01-01
    相关资源
    最近更新 更多