Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

unit testing - 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?

question from:https://stackoverflow.com/questions/3172998/moq-verify-that-no-methods-were-called

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...