如何使用 Moq 修改模拟方法的调用参数?

发布于 2024-08-20 03:31:02 字数 815 浏览 3 评论 0原文

是否可以修改模拟方法的调用参数?特别是,我希望将以下示例中的 buffer 更改为预填充的字节数组。

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

说明:
调用 Read 将从 offset 读取的 count 个字节加载到提供的字节数组 buffer 中。

现在,我希望在应用程序代码中调用 Read 后填充缓冲区。这可能吗?

如果是,我将如何连续调用 Read?如果可能的话,我希望连续的调用每次都返回不同的缓冲区。

编辑:

使用像这样的 Setup 命令:

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

在执行单元时给我一个奇怪的问题测试:调用 Read 并执行委托代码 (buffer[0] = 0xAA) 后,调试器显示 buffer实际上 null 并且单元测试执行在执行此命令后停止。是我的语法被破坏还是这是一个错误?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心作怪 2024-08-27 03:31:02

您可以使用回调方法。像这样的(凭记忆):

var buffer = new byte[64];
// ...
mock.Setup(m => m.Read(buffer, offset, count))
    .Callback((buffer, offset, count) => /* fill in buffer here */);

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 */);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文