3

Eg: I have an interface with a property and a method. The method does something with the value of the property. How do I setup the mock to access the value of property?

interface myInterface
{
    Id{get;set;}
    string ReturnIdAsString();
}

Mock<myInterface> mock = new Mock<myInterface>();
mock.Setup(m => m.Id).Returns(1);
mock.Setup(m => m.ReturnsIdAsString).Returns(**would like to return m.Id here**);

mock.Object.ReturnsIdAsString(); //should return the value in m.Id 

How do I setup ReturnsIdAsString to access the property Id?

Raj Rao
  • 8,872
  • 12
  • 69
  • 83

1 Answers1

7

You use SetupGet for properties. Since you're mocking an interface, there won't be any underlying implementation, and you'll have to set up the method too.

Mock<myInterface> mock = new Mock<myInterface>(){CallBase = true};
mock.SetupGet(m => m.Id).Returns(1);
mock.Setup(m => m.ReturnsIdAsString()).Returns("1");

You could alternatively make the method use a lambda on its return, if you're intending to change the return value of the Id property.

mock.Setup(m => m.ReturnsIdAsString()).Returns(() => mock.Object.Id.ToString());

Remember that even if your class calls m.Id = 42 it won't change the Get of the property, though you can verify a Set.

mock.VerifySet(m => m.Id = 42);
Lunivore
  • 17,277
  • 4
  • 47
  • 92