简体   繁体   中英

Strange behavior in the “Verify” method in Moq

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).

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] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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