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

无人久伴 提交于 2020-01-02 00:52:13

问题


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:


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


来源:https://stackoverflow.com/questions/2183691/how-to-modify-an-invocation-parameter-of-a-mocked-method-with-moq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!