moq Mocking properties Auto stubbing properties

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Sometimes you want to mock a class or an interface and have its properties behave as if they were simple getters and setters. As this is a common requirement, Moq provides a short cut method to setup all properties of a mock to store and retrieve values:

// SetupAllProperties tells mock to implement setter/getter funcationality
var userMock = new Mock<IUser>().SetupAllProperties();

// Invoke the code to test
SetPropertiesOfUser(userMock.Object);

// Validate properties have been set
Assert.AreEqual(5, userMock.Object.Id);
Assert.AreEqual("SomeName", userMock.Object.Name);

For completeness, the code being tested is below

void SetPropertiesOfUser(IUser user)
{
    user.Id = 5;
    user.Name = "SomeName";
}


Got any moq Question?