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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With