Using Moq, how do I set up a method call with an input parameter as an object with expected property values?
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();
You can use the It.Is method:
storageManager.Setup(e => e.Add(It.Is<UserMetaData>(data => data.FirstName == "FirstName1")));
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.