views:

176

answers:

1

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

+4  A: 

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

womp