What is the purpose of VerifyAll() in Moq?

Unit TestingMoq

Unit Testing Problem Overview


I read the question at https://stackoverflow.com/questions/980554/what-is-the-purpose-of-verifiable-in-moq and have this question in my mind:

What is the purpose of VerifyAll() in Moq?

Unit Testing Solutions


Solution 1 - Unit Testing

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

Solution 2 - Unit Testing

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNam G VUView Question on Stackoverflow
Solution 1 - Unit TestingemaView Answer on Stackoverflow
Solution 2 - Unit TestingOlegIView Answer on Stackoverflow