tags:

views:

1437

answers:

5

How do I verify that method was NOT called in Moq?

Does it have something like AssertWasNotCalled?

UPDATE: Starting from Version 3.0, a new syntaxt can be used:

mock.Verify(foo => foo.Execute("ping"), Times.Never());
A: 

Use .AtMostOnce();

After the real test, call the method again. If it throws an exception, it was called.

Aaron Digulla
Isn't a little bit too obscure, to assert that exception was thrown by mocking framework?
alex
Why? Just check the type of the exception. If it's one thrown my Moq, you're safe.
Aaron Digulla
+17  A: 

Either, make your mock strict so it will fail if you call a method for which you don't have an expect

new Mock<IMoq>(MockBehavior.Strict)

Or, if you want your mock to be loose, use the .Throws( Exception )

var m = new Mock<IMoq>(MockBehavior.Loose);
m.Expect(a => a.moo()).Throws(new Exception("Shouldn't be called."));
Dan Fish
... or Callback() to set some flag that can be asserted.
alex
Also with option#2, you can't have a VerifyAll in a general Teardown method - it will fail saying that the expectation was not met ; when the test should ideally pass.
Gishu
This isn't really a "verify not called" as it could be caught within the method and would still work - providing a false positive!
burnt_hand
+7  A: 

Actually, it's better to specify .AtMost(0) after the Returns statement.

var m = new Mock<ISomething>();
m.Expect(x => x.Forbidden()).Returns("foo").AtMost(0);

Although the "throws" also works, AtMost(0) is more expressive IMHO.

Edit This does not work in recent versions of Moq (since at least 3.1), it should be specified in the Verify method as mentioned in the answer.

miha
can't find this in Moq v3.1
Gishu
won't work for methods that don't have a return value
joshperry
+3  A: 

Stolen from: http://stackoverflow.com/questions/1073846/need-help-understand-moq-better/1080774#1080774

One of the things that you might want to test is that the pay method does not get called when a person aged over 65 is passed into the method

[Test]
public void Someone_over_65_does_not_pay_a_pension_contribution() {
    Mock<IPensionService> mockPensionService = new Mock<IPensionService>();
    Person p = new Person("test", 66);
    PensionCalculator calc = new PensionCalculator(mockPensionService.Object);
    calc.PayPensionContribution(p);
    mockPensionService.Verify(ps => ps.Pay(It.IsAny<decimal>()), Times.Never());
}
Chris Marisic
+3  A: 

Run a verify after the test which has a "Times.Never" enum set. e.g.

_mock.Object.DoSomething()
_mock.Verify(service => service.ShouldntBeCalled(),Times.Never());
burnt_hand
realised this was in the question after figuring it out. Leaving it here so people dont make the same mistake as me
burnt_hand