如何正确模拟一个已模拟类的属性?

huangapple go评论88阅读模式
英文:

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())).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 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

根据您的需求而定。请注意,第一个示例需要正确使用 SetupPropertySetupAllProperties文档):

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&lt;IFoo&gt;();
// mock.SetupProperty(f =&gt; f.Name);
// mock.SetupAllProperties();
IFoo foo = mock.Object;

foo.Name = &quot;bar&quot;;
Assert.AreEqual(&quot;bar&quot;, 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".

huangapple
  • 本文由 发表于 2023年5月25日 17:43:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76330921.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定