设置如下:
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())
pass.
因为这可能构成起订量/单元测试滥用,所以我的理由是我可以做这样的事情:
[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 并执行我的断言 - 除了验证调用之外,我可以执行所有这些操作。
现在起订量支持此功能
Use .Invocations.Clear()
在该库的最新版本上:
var foo = new Mock<foo>();
foo.Invocations.Clear();
旧答案
我认为在这篇文章创建很久之后,他们添加了 OP 要求的功能,有一个名为 Moq 扩展方法Moq.MockExtensions.ResetCalls().
通过这种方法,您可以完全按照您的意愿进行操作,如下所示:
[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());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)