The bounty expires in 3 days. Answers to this question are eligible for a
+300 reputation bounty.
user919426 is looking for an
up-to-date answer to this question:
The current answer is old. I would like to do the same based on the Microsoft Aysnc Client Socket example (docs.microsoft.com/en-us/dotnet/framework/network-programming/…):
I am trying to convert the example to a non-static class that processes a collection of messages AND gets the results for each item.
Also, would it be more expensive to open, send and close the connection for each message? Or is it better to open the connection, iterate and send each message then close connection?
Is it possible to unit test the Asyn. socket programming (using c#)? Provide some sample unit test code.
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();
}