这是我在 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());
我真正想做的是相当于......
this.postService.VerifyNoMethodsCalled();
...我感兴趣的是我的控制器不会调用服务上的任何方法。使用起订量可以吗?
您可以使用 MockBehavior.Strict 创建模拟,例如
this.postService = new Mock<IPostService>(MockBehavior.Strict);
这样,如果您不设置任何期望,任何对
this.postService
的调用都会失败
mock.VerifyNoOtherCalls();
该方法确保除了任何先前验证的调用之外没有进行任何调用。在这种特殊情况下,前面没有
mock.Verify(...)
语句。因此,它将确保模拟从未被调用过。
如果拨打任何电话,您将收到如下失败消息:
This mock failed verification due to the following unverified invocations:
...
这不需要使模拟变得严格。
来源:起订量快速入门