C# 一种UDP算法的集成测试

C# 一种UDP算法的集成测试,c#,udpclient,C#,Udpclient,我需要创建一个集成测试,演示如何成功地将UDP数据包发送到远程软件。远程软件在测试环境中不可用(这是一个遗留但仍然支持的版本),并且不在我的控制之下,所以我想我应该设置一个测试,至少可以证明命令按预期运行。阅读后,我将代码设置如下: public void TestRemoteCommand() { //A "strategy picker"; will instantiate a version-specific //implementation, us

我需要创建一个集成测试,演示如何成功地将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());
    }
public void TestRemoteCommand()
{
//“策略选择器”将实例化特定于版本的
//实现,在本例中使用UdpClient
var communicator=new NotifyCommunicator(IPAddress.Loopback.ToString(),“1.0”);
const string message=“远程命令”;
常量int端口=;
var receivingEndpoint=新的IPEndPoint(IPAddress.Loopback,端口);
//我的测试侦听器;将在已通过连接到的同一端口上侦听
//通讯器的UdpClient(设置时不共享)
var client=new UdpClient();
client.client.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress,true);
client.client.Bind(receivingEndpoint);
//发送UDP关系图的结果
communicator.SendRemoteCommand();
//这种断言总是失败的
Assert.IsTrue(client.Available>0);
var结果=client.Receive(参考receivingEndpoint);
Assert.AreEqual(result.Select(b=>(char)b.ToArray(),message.toCharray());
}

然而,这并不像上面的评论那样有效。有人看到我遗漏了什么吗?

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

这就是其中的一部分。我反复研究它,发现我让它在所有端口上侦听,而不是在特定端口上侦听,这不起作用。但是,是的,我还必须加入一个快速的Thread.Sleep()语句,以确保数据包通过硬件层进入接收桶。实际上,一次运行一个测试效果很好,但在套件中失败了。