Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of VerifyAll() in Moq?

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?

like image 782
Nam G VU Avatar asked Sep 15 '10 09:09

Nam G VU


People also ask

What does MOQ VerifyAll do?

Verifies all expectations regardless of whether they have been flagged as verifiable.

What is the purpose of MOQ?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces. However, there are a few limitations you should be aware of. The classes to be mocked can't be static or sealed, and the method being mocked should be marked as virtual.

What is setup in mock?

Setup method is used to set expectations on the mock object For example: mock. Setup(foo => foo.


2 Answers

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 
like image 142
ema Avatar answered Sep 29 '22 23:09

ema


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); 
like image 32
OlegI Avatar answered Sep 29 '22 23:09

OlegI