Moq - 验证没有调用任何方法

发布于 2024-09-08 06:42:10 字数 720 浏览 3 评论 0原文

这是我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦情居士 2024-09-15 06:42:10

您可以使用 MockBehavior.Strict 创建 Mock,例如

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

这样,如果您没有设置任何期望,则对 this.postService 的任何调用都将失败

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

冰之心 2024-09-15 06:42:10

现代答案(Moq 4.8 或更高版本):

mock.VerifyNoOtherCalls();

该方法确保除了任何先前验证的调用之外没有进行任何调用。在这种特殊情况下,它之前没有 mock.Verify(...) 语句。因此,它将确保模拟从未被调用过。

如果进行任何调用,您将收到如下失败消息:

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

这不需要使模拟严格。

来源:Moq 快速入门

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文