Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test network connections?

I want to unit test the code below. I've been working with MSTest and I tried to learn Microsoft Moles and RhinoMocks. But I couldn't make neither of them help me. I know I can change the code drastically to use interfaces that make it more testable, but it would require me to code interfaces and implementations that encapsulate TcpClient, NetworkStream, StreamWriter and StreamReader.

I've already written integration test for this and I guess that someone proficient with moles can do unit tests for this quite easily without changing the code.

using (TcpClient tcpClient = new TcpClient(hostName, port))
using (NetworkStream stream = tcpClient.GetStream())
using (StreamWriter writer = new StreamWriter(stream))
using (StreamReader reader = new StreamReader(stream))
{
    writer.AutoFlush = true;
    writer.Write(message);
    return reader.ReadLine();
}
like image 734
Jader Dias Avatar asked Dec 21 '22 04:12

Jader Dias


1 Answers

Keep it simple.

Abstract away the network layer. I usually use an interface called something like INetworkChannel that looks something like this:

public interface INetworkChannel : IDisposable
{
    void Connect(IPEndPoint remoteEndPoint);
    void Send(byte[] buffer, int offset, int count);

    public event EventHandler Disconnected;
    public event EventHandler<ReceivedEventArgs> Received;
}

It makes it easy to test everything and you could create SecureNetworkChannel class which uses SslStream or FastNetworkChannel which uses the new Async methods.

The details like what stream is used or if you use TcpClient or Socket should not matter to the rest of the application.

Edit

Testing the INetworkingChannel implementation is easy too since you now got a class with a very clear responsibility. I do create a connection to my implementations to test them. Let the TcpListener listen on port 0 to let the OS assign a free port.

I just make sure that it handle sends and receives properly and that it do proper clean up when a connection is closed/broken.

like image 78
jgauffin Avatar answered Dec 31 '22 14:12

jgauffin