moq Mocking properties Auto stubbing properties


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";
}