I am trying to set a property on a mock by calling a method on it which sets the property value.
MyObject myObject = new MyObject();
Mock<IMockedClass> myMock = new Mock<IMockedClass>();
myMock.SetupAllProperties();
myMock.Object.MethodWhichSetsProperty(myObject);
Now I am expecting myMock.Object.MyProperty to be set to myObject, but its not since MethodWhichSetsProperty is never actually called when setting a breakpoint in the actual class that was mocked.
I have also tried
myMock.SetupGet(x => x.MyProperty).Returns(myObject);
But the property just returns null when used afterwards.
The class that is being mocked:
public class MockedClass : IMockedClass
{
public MyObject MyProperty { get; private set; }
public MockedClass()
{
}
public void MethodWhichSetProperty(MyObject myObject)
{
MyProperty = myObject;
}
}
CodePudding user response:
You need to set up MethodWhichSetsProperty
for the mocked class.
Something like this should work:
MyObject myObject = new MyObject();
myMock.SetupGet(x => x.MyProperty).Returns(myObject);
myMock.Setup(x => x.MethodWhichSetsProperty(It.IsAny<MyObject>())).Callback(objectToAssign => myProperty = objectToAssign);
Update with example for multiple arguments:
MyObject myObject = new MyObject();
myMock.SetupGet(x => x.MyProperty).Returns(myObject);
myMock.Setup(x => x.MethodWhichSetsProperty(It.IsAny<MyObject>(), It.IsAny<MyObject>(), It.IsAny<MyObject>()))
.Callback<MyObject, MyObject, MyObject>((myObject1, myObject2, myObject3) =>
{
//Do whatever you want in here e.g.
myProperty = myObject1.Number myObject2.Number myObject3.Number;
});
CodePudding user response:
Your class has an implementation (ie, when calling MethodWhichSetProperty
it internally sets a property) - but you're not mocking the class you're mocking the interface - and that interface knows nothing of your class implementation.
myMock.SetupGet(x => x.MyProperty).Returns(myObject);
This should absolutely work though, and can easily be demonstrated: https://dotnetfiddle.net/kUSkFl