title: How to unit test client network code?
body: <p>I'm working on a piece of networking code which listens to a TCP connection, parses the incoming data and raises the appropriate event. Naturally, to avoid blocking the rest of the application, the listening and parsing are performed in a background worker. When trying to unit test this code I run into the problem that, seeing as the network code has more work to do than the unit test, the unit test completes before the adapter has a chance to raise the event and so the test fails.</p>
  
  <p>Adapter class:</p>
  
  <pre><code>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...
          }
      }
  }
  </code></pre>
  
  <p>Attempted test code:</p>
  
  <pre><code>[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) =&gt;
      {
          newConfigurationReceived = true;
      };
  
      //Send fake byte packets to TestClient.
  
      Assert.IsTrue(newConfigurationReceived, "Results: Event not raised.");
  }
  </code></pre>
  
  <p>How should I go about trying to test this sort of thing? </p>
  
  <p>Thanks,</p>
  
  <p>James</p>