How to unit test network connections?

I want unit test code below. I worked with MSTest and I tried to learn Microsoft Moles and RhinoMocks . But I could not get any of them to help me. I know that I can change the code a lot to use interfaces that make it more testable, but that will require me to code the interfaces and implementations that encapsulate TcpClient, NetworkStream, StreamWriter and StreamReader.

I already wrote an integration test for this, and I assume that someone owning with a mole can easily perform unit tests for this 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(); } 
+4
source share
1 answer

Keep it simple.

Drain the network layer. I usually use an interface called INetworkChannel , which 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; } 

This makes it easy to test everything, and you can create a SecureNetworkChannel class that uses SslStream or FastNetworkChannel that uses the new Async methods.

Details like which thread is used, or if you are using TcpClient or Socket , should not matter to the rest of the application.

Edit

Testing the implementation of INetworkingChannel also easy, as you now have a class with a very clear responsibility. I am creating a connection with my implementations to test them. Let TcpListener listen on port 0 for the OS to assign a free port.

I just make sure that it handles the sends and receives correctly and that it clears correctly when the connection is closed / broken.

+10
source

Source: https://habr.com/ru/post/1386698/


All Articles