设置 Moq 以忽略虚拟方法
我有一个具有虚拟方法的抽象类。如果以后的实现需要覆盖该功能,则该方法是虚拟的。
但是,Moq 代理所有虚拟方法,因此我似乎无法测试编写的实际代码,而是使用该方法的 Mock 设置(当前返回默认值)。
摘要示例:
public abstract SomeAbstract
{
public abstract Format(IFormatProvider provider, string format)
{
// does some stuff i need to test
}
}
我的 NUnit 测试:
[Test]
public void Should_Set_Format_State()
{
Mock<SomeAbstract> mock = new Mock<SomeAbstract>();
mock.Object.Format(CultureInfo.CurrentCulture, "format string");
// do tests to make sure Format correctly changed the object's state
}
如何设置我的 Mock 对象以使我的虚拟 Format
方法正常工作,而不必从该方法中删除 virtual
?!也许我在这种情况下滥用了嘲笑概念。
I have an abstract class that has a virtual method. The method is virtual in the event that a later implementation needs to override that functionality.
However, Moq proxies all virtual methods so I don't seem to be able to test the actual code that's written, and instead uses the Mock setup for that method (which is currently to return the default value).
Example abstract:
public abstract SomeAbstract
{
public abstract Format(IFormatProvider provider, string format)
{
// does some stuff i need to test
}
}
My NUnit test:
[Test]
public void Should_Set_Format_State()
{
Mock<SomeAbstract> mock = new Mock<SomeAbstract>();
mock.Object.Format(CultureInfo.CurrentCulture, "format string");
// do tests to make sure Format correctly changed the object's state
}
How do I set up my Mock object to just let my virtual Format
method work, without having to remove virtual
from the method?! Perhaps I'm abusing the mocking concept in this case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信在模拟上设置“CallBase = true”会起作用。请参阅快速入门的“自定义模拟行为”部分
I believe setting "CallBase = true" on the mock will work. See the "Customizing Mock Behavior" section of the Quick Start