Reputation: 13199
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.
Upvotes: 2
Views: 521
Reputation: 115763
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.
Upvotes: 2