Moq 中VerifyAll() 的用途是什么?

发布于 2024-09-19 03:08:23 字数 201 浏览 3 评论 0原文

我在 阅读了这个问题: Moq 中 Verabilible() 的目的是什么? 我心里有一个问题:

Moq 中 VerifyAll() 的目的是什么?

I read the question at What is the purpose of Verifiable() in Moq? and have this question in my mind:

What is the purpose of VerifyAll() in Moq?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

旧夏天 2024-09-26 03:08:23

VerifyAll() 用于验证是否满足所有期望。假设您有:

myMock.Setup(m => m.DoSomething()).Returns(1);
mySut.Do();
myMock.VerifyAll(); // Fail if DoSomething was not called

VerifyAll() is for verifying that all the expectations have been met. Suppose you have:

myMock.Setup(m => m.DoSomething()).Returns(1);
mySut.Do();
myMock.VerifyAll(); // Fail if DoSomething was not called
看轻我的陪伴 2024-09-26 03:08:23

我会尝试完成@ema的回答,也许会给读者更多的见解。想象一下您有模拟对象,它是您的sut的依赖项。假设它有两种方法,您希望对它们进行设置,以免出现任何异常或为您的 sut 创建各种场景:

var fooMock = new Mock<Foo>();
fooMock.Setup(f => f.Eat()).Returns("string");
fooMock.Setup(f => f.Bark()).Returns(10);

_sut = new Bar(fooMock.Object);

这就是 arrange 步骤。现在您想要运行一些您想要实际测试的方法(现在您行动):

_sut.Test();

现在您将使用VerifyAll()断言

fooMock.VerifyAll();

什么你会在这里测试吗?您将测试您的设置方法是否被调用。在这种情况下,如果 Foo.Eat()Foo.Bark() 未被调用,您将收到异常并且测试将失败。因此,实际上,您混合排列和断言步骤。另外,您无法检查它被调用的次数,您可以使用 .Verify() 来执行此操作(假设您有一些参数 Param ,其属性名为 Name< /code> 在您的 Eat() 函数中):

fooMock.Verify(f => f.Eat(It.Is<Param>(p => p.Name == "name")), Times.Once);

I will try to complete @ema's answer, probably it will give more insights to the readers. Imagine you have mocked object, which is a dependency to your sut. Let's say it has two methods and you want to set them up in order to not get any exceptions or create various scenarios to your sut:

var fooMock = new Mock<Foo>();
fooMock.Setup(f => f.Eat()).Returns("string");
fooMock.Setup(f => f.Bark()).Returns(10);

_sut = new Bar(fooMock.Object);

So that was arrange step. Now you want to run some method which you want to actually test(now you act):

_sut.Test();

Now you will assert with VerifyAll():

fooMock.VerifyAll();

What you will test here? You will test whether your setup methods were called. In this case, if either Foo.Eat() or Foo.Bark() were not called you will get an exception and test will fail. So, actually, you mix arrange and assert steps. Also, you cannot check how many times it was called, which you can do with .Verify() (imagine you have some parameter Param with property called Name in your Eat() function):

fooMock.Verify(f => f.Eat(It.Is<Param>(p => p.Name == "name")), Times.Once);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文