Search code examples
c#unit-testingtddmoq

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.


Solution

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