简体   繁体   English

Moq中“验证”方法中的奇怪行为

[英]Strange behavior in the “Verify” method in Moq

In the following code, Test1 succeeds but Test2 fails: 在以下代码中,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());
}

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! 看来Test2也应该成功!

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"? 我唯一的想法是,Verify有点聪明,足以知道从另一个测试用例调用了“ myMethod”,因此“不计算在内”吗?

BTW, even if I remove the call to Verify in Test1, the same thing happens (Test2 fails). 顺便说一句,即使我删除了Test1中对Verify的调用,也会发生相同的事情(Test2失败)。

Your SetUp method runs before every test, so it's recreating your mock before Test2. 您的SetUp方法在每次测试之前运行,因此它将在Test2之前重新创建模拟。

In Test2, you haven't done anything, so your verification fails. 在Test2中,您没有执行任何操作,因此验证失败。 You're trying to verify whether or not MyMethod has been called - and it hasn't. 您正在尝试验证是否已调用MyMethod-尚未调用。 So, fail. 所以,失败。

If you're trying to only create your mock once, you need to use [TestFixtureSetUp] . 如果您尝试仅创建一次模拟,则需要使用[TestFixtureSetUp]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM