views:

239

answers:

2

Is it possible to unit test the Asyn. socket programming (using c#)? Provide some sample unit test code.

+1  A: 

I assume you are testing some class of your own that uses .NET streams; let's call it MessageSender. Note that there is no reason to unit test the .NET streams themselves, that's Microsoft's job. You should not unit test .NET framework code, just your own.

First, make sure that you inject the stream used by MessageSender. Don't create it inside the class but accept it as a property value or constructor argument. For example:

public sealed class MessageSender
{
   private readonly Stream stream;

   public MessageSender(Stream stream)
   {
      if (stream == null)
         throw new ArgumentNullException("stream");
      this.stream = stream;
   }

   public IAsyncResult BeginSendHello(AsyncCallback callback, object state)
   {
      byte[] message = new byte[] {0x01, 0x02, 0x03};
      return this.stream.BeginWrite(
         message, 0, message.Length, callback, state);
   }

   public void EndSendHello(IAsyncResult asyncResult)
   {
      this.stream.EndWrite(asyncResult);
   }
}

Now an example test: you could test that BeginSendHello invokes BeginWrite on the stream, and sends the correct bytes. We'll mock the stream and set up an expectation to verify this. I'm using the RhinoMocks framework in this example.

[Test]
public void BeginSendHelloInvokesBeginWriteWithCorrectBytes()
{
   var mocks = new MockRepository();
   var stream = mocks.StrictMock<Stream>();
   Expect.Call(stream.BeginWrite(
      new byte[] {0x01, 0x02, 0x03}, 0, 3, null, null));
   mocks.ReplayAll();

   var messageSender = new MessageSender(stream);
   messageSender.BeginSendHello(null, null);

   mocks.VerifyAll();
}
Wim Coenen