Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Moq, how do I set up a method call with an input parameter as an object with expected property values?

 var storageManager = new Mock<IStorageManager>();   storageManager.Setup(e => e.Add(It.IsAny<UserMetaData>())); 

The Add() method expects a UserMetaData object which has a FirstName property.

I'd like to make sure that an object of type UserMetaData with the FirstName of "FirstName1" has been passed.

like image 642
The Light Avatar asked Apr 08 '13 12:04

The Light


People also ask

What is callback Moq?

Callbacks. A powerful capability of Moq is to attach custom code to configured methods and properties' getters and setters. This capability is often referred to as Callbacks.

What does Moq setup do?

Moq provides a library that makes it simple to set up, test, and verify mocks. We can start by creating an instance of the class we're testing, along with a mock of an interface we want to use.

What can be mocked with Moq?

Unit testing is a powerful way to ensure that your code works as intended. It's a great way to combat the common “works on my machine” problem. Using Moq, you can mock out dependencies and make sure that you are testing the code in isolation.

Can you mock a class with 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.


2 Answers

You can use Verify.

Examples:

Verify that Add was never called with an UserMetaData with FirstName!= "FirstName1":

storageManager.Verify(e => e.Add(It.Is<UserMetaData>(d => d.FirstName!="FirstName1")), Times.Never()); 

Verify that Add was called at least once with an UserMetaData with FirstName== "FirstName1":

storageManager.Verify(e => e.Add(It.Is<UserMetaData>(d => d.FirstName=="FirstName1")), Times.AtLeastOnce()); 

Verify that Add was called exactly once with FirstName == "Firstname1" and LastName == "LastName2":

storageManager.Setup(e => e.Add(It.Is<UserMetaData>(data => data.FirstName == "FirstName1"                                                          && data.LastName  == "LastName2")));  ...  storageManager.VerifyAll(); 
like image 197
sloth Avatar answered Oct 21 '22 12:10

sloth


You can use the It.Is method:

storageManager.Setup(e => e.Add(It.Is<UserMetaData>(data => data.FirstName == "FirstName1"))); 
like image 41
MatthiasG Avatar answered Oct 21 '22 13:10

MatthiasG