开发者

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 a开发者_如何学Gopplication 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?


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 */);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜