Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq - verify that no methods were called

This is a unit-test from one of my controllers in an ASP.NET MVC project, using NUnit and Moq:

[Test]
public void Create_job_with_modelstate_errors_fails()
{
    var job = new JobDto();
    this.controller.ModelState.AddModelError("", "");

    ActionResult result = this.controller.Create(job);

    this.jobService.Verify(p => p.SaveJob(It.IsAny<JobDto>()), Times.Never());

    // some other asserts removed for brevity
}

This works fine, but from a maintenance point of view I think this line is more verbose than it needs to be:

this.postService.Verify(p => p.SavePost(It.IsAny<PostDto>()), Times.Never());

What i'd really like to be able to do is something equivalent to...

this.postService.VerifyNoMethodsCalled();

...as all i'm interested in is that my controller doesn't call any methods on the service. Is this possible using Moq?

like image 371
richeym Avatar asked Jul 03 '10 22:07

richeym


People also ask

How do you know if mocked method called?

Mockito verify() method can be used to test number of method invocations too. We can test exact number of times, at least once, at least, at most number of invocation times for a mocked method.

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 can be mocked with MOQ?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces. However, there are a few limitations you should be aware of. The classes to be mocked can't be static or sealed, and the method being mocked should be marked as virtual.


2 Answers

You could create the Mock with MockBehavior.Strict, e.g.

this.postService = new Mock<IPostService>(MockBehavior.Strict);

That way, if you don't Setup any expectations, any calls to this.postService will fail

like image 128
Patrick McDonald Avatar answered Nov 15 '22 10:11

Patrick McDonald


Modern answer (Moq 4.8 or later):

mock.VerifyNoOtherCalls();

That method makes sure no calls were made except for any previously verified ones. In this particular case, there are no mock.Verify(...) statements before it. Thus, it will make sure the mock was never called at all.

You will get a failure message like this if any calls were made:

This mock failed verification due to the following unverified invocations:
...

This does not require making the mock strict.

Source: Moq Quickstart

like image 5
MarredCheese Avatar answered Nov 15 '22 10:11

MarredCheese