What is the purpose of VerifyAll() in Moq?

穿精又带淫゛_ 提交于 2019-12-18 13:52:20

问题


I read the question at What is the purpose of Verifiable() in Moq? and have this question in my mind. Need your help to explain that.


回答1:


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

HTH




回答2:


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);


来源:https://stackoverflow.com/questions/3716561/what-is-the-purpose-of-verifyall-in-moq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!