Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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; }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading