如何使用 Moq 模拟具体对象上的函数调用?
我怎样才能在最小起订量中做到这一点?
Foo bar = new Foo();
Fake(bar.PrivateGetter).Return('whatever value')
看来我只能找到如何模拟通过框架创建的对象。我只想模拟我创建的具体对象上的单个方法/属性。
在 TypeMock 中,我只需执行 Isolate.WhenCalled(bar.PrivateGetter).Returns('whatever value')
即可。
有什么想法吗?
How can I do this in Moq?
Foo bar = new Foo();
Fake(bar.PrivateGetter).Return('whatever value')
It seems I can only find how to mock an object that was created via the framework. I want to mock just a single method/property on a concrete object I've created.
In TypeMock, I would just do Isolate.WhenCalled(bar.PrivateGetter).Returns('whatever value')
.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用 Moq 创建 Mock 对象并将 CallBase 属性设置为 true 以使用对象行为。
来自起订量文档:
CallBase 被定义为“如果没有期望覆盖成员,则调用基类实现。这称为“部分模拟”。它允许模拟类的某些部分,而不必模拟所有内容。
示例代码:
You should use Moq to create your Mock object and set CallBase property to true to use the object behavior.
From the Moq documentation:
CallBase is defined as “Invoke base class implementation if no expectation overrides the member. This is called “Partial Mock”. It allows to mock certain part of a class without having to mock everything.
Sample code:
只有 TypeMock Isolator(也许还有 Moles)可以执行这些特技。普通动态模拟库可以 仅模拟虚拟和抽象成员。
Only TypeMock Isolator (and perhaps Moles) can perform these stunts. Normal dynamic mock libraries can only mock virtual and abstract members.
只要签名上的类型可见,鼹鼠也可以替换私有方法。因此,在这种情况下,它看起来像这样:
如果您正在寻找有关 Moles 的更多信息,请从 http://research.microsoft.com/en-us/projects/pex/documentation.aspx。
Moles can also replace private methods as long as the types on the signature are visible. So in this case, it would look like this:
If you are looking for more information on Moles, start with the tutorials at http://research.microsoft.com/en-us/projects/pex/documentation.aspx.