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.
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.
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.
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.
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.
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")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With