What is the purpose of VerifyAll() in Moq?
I read the question at What is the purpose of V开发者_JAVA百科erifiable() in Moq? and have this question in my mind:
What is the purpose of VerifyAll()
in Moq?
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
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);
精彩评论