views:

46

answers:

2

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?

+2  A: 

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

Patrick McDonald
Ah, thanks. I didn't know about MockBehavior.Strict.
richeym
It's very handy also for debugging when you're trying to mock something like an MVC controller context, as the error message it gives you when you don't have an expectation setup is much more intuitive than the null reference exceptions you get when using the default MockBehavior.Loose
Patrick McDonald
A: 

The great thing about Moq is how readable, and simple the set up of mocks can be. Personally, I find the usage of the Times class to be nice.

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

The above states, that under no circumstances the post service should perform a save. The best method of improving this, if you find the code tedious (though I see the readability within tests as a good thing) is to extract this method into a extension/test helper method.

Finglas