英文:
How to correctly mock a property of a mocked class?
问题
I saw something in the lines of:
var dogMock = new Mock
dogMock.Setup(d => d.Bark(It.IsAny
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 succeed though.
英文:
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.
答案1
得分: 1
根据您的需求而定。请注意,第一个示例需要正确使用 SetupProperty
或 SetupAllProperties
(文档):
var mock = new Mock<IFoo>();
// mock.SetupProperty(f => f.Name);
// mock.SetupAllProperties();
IFoo foo = mock.Object;
foo.Name = "bar";
Assert.AreEqual("bar", foo.Name); // 如果两者都被注释掉将会引发异常
public interface IFoo
{
string Name { get; set; }
}
此外,在某些情况下,SetupProperty
方法可能具有优势,因为它具有"追踪"行为 - 如果模拟的依赖项的属性被频繁操作(多次获取和设置),它将更容易设置,并且行为更接近"黑盒"。
英文:
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".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论