I\'m using Moq & NUnit as a unit test framework.
I\'ve written a method that is given a NetworkStream object as a parameter:
public static void R
Put the NetworkStream behind a simple interface (with only the calls you need) and mock that.
You cannot mock the NetworkStream
with moq since it is not an abstract class or an interface. You can however create an abstraction on top of it and change your method to accept an instance of that abstraction. It could be something like this:
public interface IMyNetworkStream
{
int Read([In, Out] byte[] buffer, int offset, int size);
bool DataAvailable {get;}
}
Now you create a class that implements the interface:
public class MyNetworkStream : IMyNetworkStream
{
private NetworkStream stream;
public MyNetworkStream(NetworkStream ns)
{
if(ns == null) throw new ArgumentNullException("ns");
this.stream = ns;
}
public bool DataAvailable
{
get
{
return this.stream.DataAvailable;
}
}
public int Read([In, Out] byte[] buffer, int offset, int size)
{
return this.stream.Read(buffer, offset, size);
}
}
Now you can change your method signature to use an instance of IMyNetworkStream
and use Moq to create a mock of IMyNetworkStream
.
As suggested in the comments - is it possible for you to change the type to Stream, so that you, during testing, can pass a MemoryStream instead?