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

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

The Add() method expect

3条回答
  •  -上瘾入骨i
    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(); 
     storageManager
        .Setup(e => e.Add(It.IsAny()))
        .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.

提交回复
热议问题