Coder Perfect

How can I know if a method was called in Moq?


How can I make sure that method wasn’t used in Moq?

Is there something similar to AssertWasNotCalled?

UPDATE: As of Version 3.0, a new syntax is available:

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

Asked by alex

Solution #1

After you’ve completed the test, use the Times to double-check your work. Never() is a useful option.

_mock.Verify(service => service.ShouldntBeCalled(), Times.Never());

Answered by Dan

Solution #2

UPDATE: Since version 3, see the question’s update or Dann’s response below.

Either make your fake rigid or have it fail if you call a method that you don’t expect.

new Mock<IMoq>(MockBehavior.Strict)

Use the if you want your parody to be loose. flings ( Exception )

var m = new Mock<IMoq>(MockBehavior.Loose);
m.Expect(a => a.moo()).Throws(new Exception("Shouldn't be called."));

Answered by Dan Fish

Solution #3

Taken from: John Foster’s response to the query, “Need help to better grasp Moq”

Answered by Chris Marisic

Solution #4

It’s actually preferable to specify. After the Returns statement, use AtMost(0).

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

Although “throws” also work, AtMost(0) is, in my opinion, more expressive.

Answered by miha

Solution #5

Let’s say you have this way and you want to make sure it isn’t being used.

var databaseSessionMock = new Mock<IDatabaseSession>();
databaseSessionMock.Setup(m => m.Commit()).Returns(true).Verifiable();

You can perform a test like this.

databaseSessionMock.Verify(m => m.Commit(It.IsAny()), Times.Never(), "Database Session mock object was not used");

Answered by Zia Qammar

Post is based on