MOQ - 如何手动创建使用SetupGet / SetupSet一个支持的属性? [英] MOQ - how to manually create a backing property using SetupGet/SetupSet?
问题描述
我知道我们可以称之为 SetupAllProperties()
来自动创建的支持性能。但是,这是过于严格,因为它不会让我在的getter / setter方法执行额外的代码。例如,我想创建一个moq'd二传手调用其他方法/事件/逻辑。
I know we can call SetupAllProperties()
to automatically create backing properties. But this is too restrictive, because it doesn't allow me to execute additional code in the getter/setters. For example, I'd like to create a moq'd setter that invokes some other method/event/logic.
下面的代码示例重现问题
The Following code sample reproduces the issue
public interface IA
{
int B { get; set; }
};
class Test
{
[Test]
public void BackingPropertyTest()
{
int b = 1;
var mockA = new Mock<IA>();
//mockA.SetupAllProperties();
mockA.SetupGet(m => m.B).Returns(b);
mockA.SetupSet(m => m.B).Callback(val => b = val);
mockA.Object.B = 2;
Assert.AreEqual(2, b); // pass. b==2
Assert.AreEqual(2, mockA.Object.B); // fail. mockA.Object.B==1, instead of 2
}
}
由于吸气剂是设置返回局部变量的值(我想现在是一个捕获变量),我希望看到 mockA.Object.B == 2
。但是,相反,它是 1
。
Since the getter is setup to return the value of the local variable (which I guess is now a captured variable), I'd expect to see mockA.Object.B == 2
. But instead, it's 1
.
我在这里从根本上失去了一些东西?或者这是一个错误最小起订量?我跑起订量4.0.10501.6
Am I fundamentally missing something here? Or is this a MOQ bug? I'm running MOQ 4.0.10501.6
推荐答案
这是简单的解决方案。
更改退换货(二)收益(()=> b)相反,为了让'b'捕获的变量,而不是仅仅通过值传递给方法的变量。
Change Returns(b) to Returns(() => b) instead, in order to make 'b' a captured variable instead of just a variable passed by value to a method.
这篇关于MOQ - 如何手动创建使用SetupGet / SetupSet一个支持的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!