views:

118

answers:

1

I am trying out moq and I have a question regarding to the Setup() method. I have the following interface and class:

public interface IMyInterface
{
    void Print(string name);
}
public class MyClass
{
    private IMyInterface my;
    public MyClass(IMyInterface my)
    {
        this.my = my;
    }

    public void Print()
    {
        my.Print("hello world");
    }
}

And I’ve got this unit test using NUnit:

[Test]
public void AnotherTest()
{
    var mock = new Mock<IMyInterface>();
    mock.Setup(m => m.Print("hello world")).AtMostOnce();

    var myClass = new MyClass(mock.Object);
    myClass.Print();

    mock.Verify(m => m.Print("hello world"), Times.Exactly(1));
}

I’ve tried to both comment/uncomment out the below line and both tests were successful. It makes me wonder if Setup() is necessary in this case since I am doing the Verify()?

I am using version 3.5.716.1.

+2  A: 

In your first example, you are correct, you don't need to call the setup as you're verifying that the setup executed exactly once.

However in your second unit test, it passes because you don't actually verify your setups.

If you call mock.VerifyAll() the test will fail.

The AtMostOnce() sets an expectation that it will only ever get executed once. The test will only fail when you explicitly verify that the setup was called once. It won't actually fail just because you call it more than once.

lomaxx
Yes, I just realized why the test passed regarding to the 2nd quetsion.
Jeffrey C
It seems to me that manually verifying all the scenarios is more explicit than Setting up the behaviour then do VerifyAll().
Jeffrey C