“验证”中的奇怪行为 最小起订量方法
在下面的代码中,Test1 成功,但 Test2 失败:
protected Mock<IMyInterface> MyMock { get; set; }
[SetUp]
public virtual void Initialize()
{
MyMock = new Mock<IMyInterface>();
}
[Test]
void Test1()
{
// ... code that causes IMyIntervace.myMethod to be called once
MyMock.Verify(x=> x.myMethod(), Times.Once());
}
[Test]
void Test2()
{
MyMock.Verify(x=> x.myMethod(), Times.Once());
}
这种行为实际上非常有用,但我不明白为什么它会这样工作。 看来Test2也应该成功了!
我唯一的想法是,Verify 足够聪明,知道“myMethod”是从不同的测试用例中调用的,所以它“不算数”?
顺便说一句,即使我在 Test1 中删除对 Verify 的调用,也会发生同样的事情(Test2 失败)。
In the following code, Test1 succeeds but Test2 fails:
protected Mock<IMyInterface> MyMock { get; set; }
[SetUp]
public virtual void Initialize()
{
MyMock = new Mock<IMyInterface>();
}
[Test]
void Test1()
{
// ... code that causes IMyIntervace.myMethod to be called once
MyMock.Verify(x=> x.myMethod(), Times.Once());
}
[Test]
void Test2()
{
MyMock.Verify(x=> x.myMethod(), Times.Once());
}
This behavior is actually quite useful but I can't figure out why it's working like this. It seems like Test2 should also succeed!
The only idea I have is that somehow Verify is smart enough to know that "myMethod" was called from a different test case and so it "doesn't count"?
BTW, even if I remove the call to Verify in Test1, the same thing happens (Test2 fails).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 SetUp 方法在每个测试之前运行,因此它会在 Test2 之前重新创建您的模拟。
在 Test2 中,您没有执行任何操作,因此验证失败。 您试图验证 MyMethod 是否已被调用 - 但它没有被调用。 所以,失败。
如果您尝试只创建一次模拟,则需要使用
[TestFixtureSetUp]
。Your SetUp method runs before every test, so it's recreating your mock before Test2.
In Test2, you haven't done anything, so your verification fails. You're trying to verify whether or not MyMethod has been called - and it hasn't. So, fail.
If you're trying to only create your mock once, you need to use
[TestFixtureSetUp]
.