MOQ - how to manually create a backing property using SetupGet/SetupSet?

ぃ、小莉子 提交于 2019-12-12 07:56:04

问题


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
    }
}

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.

Am I fundamentally missing something here? Or is this a MOQ bug? I'm running MOQ 4.0.10501.6


回答1:


An easy solution.

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.



来源:https://stackoverflow.com/questions/5578269/moq-how-to-manually-create-a-backing-property-using-setupget-setupset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!