Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock Networkstream.Read

Tags:

c#

.net

stream

tdd

I've been trying to mock a network stream for some unit tests.

So far, using Moq the best I've come up with is to use a wrapper for the stream and then mock my interface.

public interface INetworkstreamWrapper
{
    int Read(byte[] buffer, int offset,int size);

    void Flush();

    bool DataAvailable { get; }

    bool CanRead { get; }

    void close();
}

Question is, whilst that gives me a start, I actually want to test some byte array values as read into my read buffer. How can I return some test data into the buffer when calling Read() on the mock object?

like image 581
obaylis Avatar asked Nov 10 '12 22:11

obaylis


People also ask

How do I read data from a networkstream?

The Read operation reads as much data as is available, up to the number of bytes specified by the size parameter. Check to see if the NetworkStream is readable by calling the CanRead property. If you attempt to read from a NetworkStream that is not readable, you will get an InvalidOperationException.

What is an async read from networkstream?

Sockets Begins an asynchronous read from the NetworkStream. An array of type Byte that is the location in memory to store data read from the NetworkStream. The location in buffer to begin storing the data. The number of bytes to read from the NetworkStream.

Why does the networkstream not support reading?

The NetworkStream does not support reading. An error occurred when accessing the socket. There is a failure reading from the network. The NetworkStream is closed. This method reads as much data as is available into the buffer parameter and returns the number of bytes successfully read.

Is the networkstream open or closed?

The NetworkStream is closed. The following code example uses DataAvailable to determine if data is available to be read. If data is available, it reads from the NetworkStream. // Examples for CanRead, Read, and DataAvailable.


1 Answers

You can use a callback to gain access to the passed parameter and alter them:

public void TestRead()
{
  var streamMock = new Mock<INetworkstreamWrapper>();

   streamMock
            .Setup(m => m.Read(It.IsAny<byte[]>(), 
                               It.IsAny<int>(), 
                               It.IsAny<int>()))
            .Callback((byte[] buffer, int offset, int size) => buffer[0] = 128);

   var myBuffer = new byte[10];
   streamMock.Object.Read(myBuffer,0,10);

   Assert.AreEqual(128, myBuffer[0]);
}

But I would suggest you rethink your strategy about that kind of mocking, see: http://davesquared.net/2011/04/dont-mock-types-you-dont-own.html

Maybe you could write an integration test instead, or make your code depend on the abstract Stream class.

In your test you could then use a MemoryStream to check your class correct behaviour when fetching data from the Stream.

like image 98
foobarcode Avatar answered Oct 10 '22 21:10

foobarcode