这样设置:
public interface IFoo
{
void Fizz();
}
[Test]
public void A()
{
var foo = new Mock<IFoo>(MockBehavior.Loose);
foo.Object.Fizz();
foo.Verify(x => x.Fizz());
// stuff here
foo.Verify(x => x.Fizz(), Times.Never()); // currently this fails
}
基本上,我想在 //stuff here
处输入一些代码来生成 foo.Verify(x => x.Fizz(), Times.Never())
通过。
因为这可能构成最小起订量/单元测试滥用,我的理由是我可以做这样的事情:
[Test]
public void Justification()
{
var foo = new Mock<IFoo>(MockBehavior.Loose);
foo.Setup(x => x.Fizz());
var objectUnderTest = new ObjectUnderTest(foo.Object);
objectUnderTest.DoStuffToPushIntoState1(); // this is various lines of code and setup
foo.Verify(x => x.Fizz());
// reset the verification here
objectUnderTest.DoStuffToPushIntoState2(); // more lines of code
foo.Verify(x => x.Fizz(), Times.Never());
}
基本上,我有一个状态对象,需要做一些工作(包括制作各种模拟对象和其他杂乱无章的东西)才能将它插入 State1。然后我想测试从 State1 到 State2 的转换。与其复制或抽象代码,我更愿意重新使用 State1 测试,将其推送到 State2 并执行我的断言 - 除了验证调用之外,我可以做所有这些。
最佳答案
现在在 Moq 中支持
在最新版本的库上使用 .Invocations.Clear()
:
var foo = new Mock<foo>();
foo.Invocations.Clear();
旧答案
我想在创建这篇文章很久之后,他们添加了 OP 要求的功能,有一个名为 Moq.MockExtensions.ResetCalls() 的 Moq 扩展方法。
使用此方法,您可以完全按照自己的意愿进行操作,如下所示:
[Test]
public void Justification()
{
var foo = new Mock<IFoo>(MockBehavior.Loose);
foo.Setup(x => x.Fizz());
var objectUnderTest = new ObjectUnderTest(foo.Object);
objectUnderTest.DoStuffToPushIntoState1(); // this is various lines of code and setup
foo.Verify(x => x.Fizz());
foo.ResetCalls(); // *** Reset the verification here with this glorious method ***
objectUnderTest.DoStuffToPushIntoState2(); // more lines of code
foo.Verify(x => x.Fizz(), Times.Never());
}
关于c# - 在最小起订量中重置模拟验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4163679/