Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 682
stoj Avatar asked Apr 07 '11 08:04

stoj


1 Answers

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.

mockA.SetupGet(m => m.B).Returns(() => b);
like image 56
stoj Avatar answered Nov 16 '22 14:11

stoj