Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify that method was NOT called in Moq?

Tags:

c#

.net

moq

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 syntax can be used:

mock.Verify(foo => foo.Execute("ping"), Times.Never()); 
like image 617
alex Avatar asked Feb 11 '09 15:02

alex


People also ask

What is verifiable in Moq?

Verifiable(); 'Setup' mocks a method and 'Returns' specify what the mocked method should return. 'Verifiable' marks this expectation to verified at the end when Verify or VerifyAll is called i.e. whether AddIncomePeriod was called with an object of IncomePeriod and if it returned the same output.

What is callback in Moq?

Callbacks. A powerful capability of Moq is to attach custom code to configured methods and properties' getters and setters. This capability is often referred to as Callbacks.


2 Answers

Run a verify after the test with the Times.Never() option.

_mock.Object.DoSomething() _mock.Verify(service => service.ShouldntBeCalled(), Times.Never()); 
like image 86
Dan Avatar answered Oct 16 '22 12:10

Dan


UPDATE: Since version 3, check the update to the question above or Dann's answer below.

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.")); 
like image 32
Dan Fish Avatar answered Oct 16 '22 12:10

Dan Fish