Search code examples
c#propertiesmockingmoq

How to correctly mock a property of a mocked class?


I was reviewing some unit tests from a colleague, and I saw something in the lines of:

var dogMock = new Mock<Dog>();

dogMock.Setup(d => d.Bark(It.IsAny<Volume>())).Returns(someMockedBarking);
dogMock.Object.Age = 2;

Is it ok that a property of the Object is directly set, or is it better to use the Setup and Returns like the following?

dogMock.Setup(d => d.Age).Returns(2);

In both cases, the unit tests succeeds though.


Solution

  • It depends on your needs. Note that the first one requires SetupProperty or SetupAllProperties to work correctly (docs):

    var mock = new Mock<IFoo>();
    // mock.SetupProperty(f => f.Name);
    // mock.SetupAllProperties();
    IFoo foo = mock.Object;
    
    foo.Name = "bar";
    Assert.AreEqual("bar", foo.Name); // Throws if both commented out
    
    public interface IFoo
    {
        string Name { get; set; }
    }
    

    Also in some cases the SetupProperty approach can have advantages due it's "tracking" behavior - if the mocked dependency has it's property heavily manipulated (multiple gets and sets are performed) it will allow easier setup and behaviour closer to "black box".