side effects and mocked objects

11 views
Skip to first unread message

Robert Ream

unread,
Feb 4, 2008, 1:27:25 PM2/4/08
to Rhino...@googlegroups.com
How would I mock a method like Stream.Read. The Read method on the
Stream class alters the values in the array passed in as the first
argument. I tried this:

Expect.Call(stream.Read(new byte[1024], 0, 1024))
.Do(delegate(byte[] buffer, int offset, int count) { return 0; });

But the compiler doesn't like it.
Any suggestions? I'd prefer to not use a partial mock.

Owen Evans

unread,
Feb 4, 2008, 1:34:27 PM2/4/08
to Rhino...@googlegroups.com
the delegate has to be cast to a specific delegate type in C#

delegate int ReadDelegate(byte[] buffer, int start, int end);

then use this delegate in the Expect

Expect.Call(stream.Read(new byte[1024], 0, 1024))
.Do((ReadDelegate) myDelegateFunction);

myDelegateFunction is declared with the same signature as the delegate:

myDelegateFunction(byte[] buffer, int start, int end)
{
return 0;
}

alternatively you can use c# lambdas in vs2008



Expect.Call(stream.Read(new byte[1024], 0, 1024))
.Do((ReadDelegate) ( (byte[] buffer, int start, int end)=>{
return 0;}  ));


apologies if I've missed something, but straight off that's my suggestion.

cheers
O

Robert Ream

unread,
Feb 4, 2008, 2:09:47 PM2/4/08
to Rhino...@googlegroups.com
Thank you,

Is there any technical limitations on to why anonymous functions
couldn't be made to work?

Steve Freeman

unread,
Feb 4, 2008, 3:40:16 PM2/4/08
to Rhino...@googlegroups.com
I would strongly recommend not mocking a stream like this, unless
you're doing something very precise. It's too low level so the tests
will be brittle. An alternative would be to use something like a
StringReader.

S.


Steve Freeman
http://www.mockobjects.com

Winner of the Agile Alliance Gordon Pask award 2006

Reply all
Reply to author
Forward
0 new messages