views:

106

answers:

1

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?

+1  A: 

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 */);
Mark Seemann
Hi Mark. Thanks for the answer. If I use this pattern my unit test will just stop at the very point in the callback when the delegate is executed. Debugging the issue showed that the buffer byte array is `null`. Any ideas why that might happen?
Timo Kosig
It's null unless you assign it. The above Setup call doesn't *assign* the buffer variable - it matches an existing variable. In your edit you match on `It.IsAny<byte[]>()`, but the caller must still supply the value.
Mark Seemann