如何单元测试客户端网络代码?

Moo*_*eld 4 c# multithreading unit-testing client-server

我正在研究一个侦听TCP连接的网络代码,解析传入的数据并引发相应的事件.当然,为了避免阻塞应用程序的其余部分,监听和解析是在后台工作程序中执行的.当试图对这段代码进行单元测试时,我遇到的问题是,由于网络代码比单元测试有更多工作要做,因此单元测试在适配器有机会引发事件之前完成,因此测试失败.

适配器类:

public class NetworkAdapter : NetworkAdapterBase //NetworkAdapterBase is just an abstract base class with event definitions and protected Raise... methods.
{
    //Fields removed for brevity.

    public NetworkAdapter(TcpClient tcpClient)
    {
        _tcpConnection = tcpClient;

        //Hook up event handlers for background worker.
        NetworkWorker.DoWork += NetworkWorker_DoWork;

        if (IsConnected)
        {
            //Start up background worker.
            NetworkWorker.RunWorkerAsync();
        }
    }

    private void NetworkWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        while (IsConnected)
        {
            //Listen for incoming data, parse, raise events...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

试图测试代码:

[TestMethod]
public void _processes_network_data()
{
    bool newConfigurationReceived = false;

    var adapter = new NetworkAdapter(TestClient); //TestClient is just a TcpClient that is set up in a [TestInitialize] method.

    adapter.ConfigurationDataReceived += (sender, config) =>
    {
        newConfigurationReceived = true;
    };

    //Send fake byte packets to TestClient.

    Assert.IsTrue(newConfigurationReceived, "Results: Event not raised.");
}
Run Code Online (Sandbox Code Playgroud)

我该如何尝试测试这种东西?

谢谢,

詹姆士

Kei*_*thS 6

嗯,首先,这不是一个严格的"单元测试"; 您的测试取决于具有副作用的体系结构层,在这种情况下传输网络数据包.这更像是一次集成测试.

也就是说,正如托尼所说,你的单元测试可以睡一定数量的毫安.您还可以看到是否可以获得后台工作程序的句柄,并加入它,这将导致您的单元测试等待后台工作程序完成所需的时间.