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

I know that we can call SetupAllProperties() to automatically create backup properties. But this is too restrictive because it does not allow me to execute additional code in getter / seters. For example, I would like to create a moq'd installer that calls another method / event / logic.

The following code example reproduces the problem

 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 => mB).Returns(b); mockA.SetupSet(m => mB).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 getter is configured to return the value of a local variable (which I assume is now a captured variable), I expect to see mockA.Object.B == 2 . But instead he is 1 .

Am I basically missing something? Or is it a MOQ error? I am running MOQ 4.0.10501.6

+7
source share
1 answer

Easy solution.

Change return (b) to Returns (() => b) instead to make "b" the captured variable instead of the variable passed by value to the method.

+13
source

All Articles