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();
}
Keep it simple.
Abstract away the network layer. I usually use an interface called something like
INetworkChannelthat looks something like this:It makes it easy to test everything and you could create
SecureNetworkChannelclass which usesSslStreamorFastNetworkChannelwhich uses the new Async methods.The details like what stream is used or if you use
TcpClientorSocketshould not matter to the rest of the application.Edit
Testing the
INetworkingChannelimplementation 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 theTcpListenerlisten on port0to 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.