Remove setup from mock.

3,844 views
Skip to first unread message

mirle

unread,
Nov 26, 2012, 10:37:32 AM11/26/12
to moq...@googlegroups.com
Hi guys,

I'm mocking a concrete class with virtual methods.
Is it possible, to remove a previously set setup, to have the calls go through to the concrete class again?

The method I'm trying to test, gets a stream from another class (HttpWebRequest.GetRequestStream), writes data to it and closes the stream.

I'm mocking the HttpWebRequest to return a MemoryStream.
The MemoryStream again is mocked to ignore Close and Dispose calls such that afterwards, I can check if the correct data was written to the stream and that Close was called.

Everythings fine, but after the whole test, I want to close the mocked MemoryStream, which I can't, because Close and Dispose are rerouted.

Any Ideas?
Thanks!

Cheeers,
M.

Sunny

unread,
Nov 27, 2012, 4:55:39 PM11/27/12
to moq...@googlegroups.com
Instead of returning MemoryStream, why don't you return just a Mock<Stream> and verify if the appropriate methods were called with the right data.

Something like:
var recievedData = new MemoryStream();

var mockStream = new Mock<Stream>(MockBehavior.Strict);
mockStream.Setup(s=>s.Write(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>())
.CallBack((byte[] buffer, int offset, int count) => receivedData.Write(buffer, offset, count)));
mockStream.Setup(s=>s.Close()).Verifialble();

... do your test here
mockStream.VerifyAll(); // to check close was called
...verify the data in recievedData
recievedData.Close();

Cheers,
Sunny





--
Svetoslav Milenov (Sunny)

Artificial Intelligence is no match for natural stupidity.

mirle

unread,
Nov 29, 2012, 4:27:34 PM11/29/12
to moq...@googlegroups.com
Ah, didn't think about that.

Works like a charm.
Thanks!

Cheers,
M.
Reply all
Reply to author
Forward
0 new messages