Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify an invocation parameter of a mocked method with Moq?

Is it possible to modify an invocation parameter of a mocked method? In particular I'm looking to change buffer in the following example to a pre-populated byte array.

Example:
int MockedClass.Read(byte[] buffer, int offset, int count)

Explanation:
Calling Read loads count bytes reading from offset into the supplied byte array buffer.

Now I would like to have buffer populated after the call to Read has been made in my application code. Is that possible?

If yes, how would I go about successive calls to Read? I would like successive calls to return a different buffer each time if possible.

EDIT:

using the Setup command like this:

MockedClass.Setup(x => x.Read(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()).Callback( (byte[] buffer, int offset, int count) => buffer[0] = 0xAA);

gives me a weird problem when executing the unit test: Once the call to Read is made and the delegate code (buffer[0] = 0xAA) is executed the debugger shows that buffer is actually null and the unit test execution stops after executing this command. Is my syntax borked or is that a bug?

like image 205
Timo Kosig Avatar asked Feb 02 '10 11:02

Timo Kosig


1 Answers

You can use the Callback method. Something like this (from memory):

var buffer = new byte[64];
// ...
mock.Setup(m => m.Read(buffer, offset, count))
    .Callback((buffer, offset, count) => /* fill in buffer here */);
like image 153
Mark Seemann Avatar answered Sep 27 '22 23:09

Mark Seemann