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

前端 未结 3 2022
一生所求
一生所求 2021-02-01 14:35
 var storageManager = new Mock(); 
 storageManager.Setup(e => e.Add(It.IsAny()));

The Add() method expect

相关标签:
3条回答
  • 2021-02-01 15:08

    Dominic Kexel's method is good and will work. You can also use callback though which is useful if you need to do any checking of the output that is more complicated.

     UserMetaData parameter = null;
     var storageManager = new Mock<IStorageManager>(); 
     storageManager
        .Setup(e => e.Add(It.IsAny<UserMetaData>()))
        .Callback((UserMetaData metaData) => parameter = metaData);
    
     Assert.That(parameter.FirstName, Is.EqualTo("FirstName1")); //If using fluent NUnit
    

    The advantage of this is that, if required, you can do many more checks on the parameter rather than just checking that it is "FirstName1".

    The disadvantage is that if Add is called multiple times then only the parameter passed in the last call will be checked (although you can additionally Verify that it was called once).

    Dominic's answer is better than mine for your precise situation but I wanted to point out Callback for other similar situations.

    0 讨论(0)
  • 2021-02-01 15:22

    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();
    
    0 讨论(0)
  • 2021-02-01 15:24

    You can use the It.Is method:

    storageManager.Setup(e => e.Add(It.Is<UserMetaData>(data => data.FirstName == "FirstName1")));
    
    0 讨论(0)
提交回复
热议问题