Moq - 验证没有调用任何方法
这是我在 ASP.NET MVC 项目中的一个控制器的单元测试,使用 NUnit 和 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.postService.Verify(p => p.SavePost(It.IsAny<PostDto>()), Times.Never());
What i我真的希望能够做的事情相当于...
this.postService.VerifyNoMethodsCalled();
...因为我感兴趣的是我的控制器不调用服务上的任何方法。使用起订量可以吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 MockBehavior.Strict 创建 Mock,例如
这样,如果您没有设置任何期望,则对
this.postService
的任何调用都将失败You could create the Mock with MockBehavior.Strict, e.g.
That way, if you don't Setup any expectations, any calls to
this.postService
will fail现代答案(Moq 4.8 或更高版本):
该方法确保除了任何先前验证的调用之外没有进行任何调用。在这种特殊情况下,它之前没有
mock.Verify(...)
语句。因此,它将确保模拟从未被调用过。如果进行任何调用,您将收到如下失败消息:
这不需要使模拟严格。
来源:Moq 快速入门
Modern answer (Moq 4.8 or later):
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 does not require making the mock strict.
Source: Moq Quickstart