Moq - access to the properties of the mocked object

For example: I have an interface with a property and a method. The method does something with the value of the property. How to configure the layout to access the value of a 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 to configure ReturnsIdAsString to access property id?

+3
source share
1 answer

You use SetupGetfor properties. Since you are mocking the interface, there will be no main implementation, and you will also have to configure this method.

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

Alternatively, you can use the lambda method when returning it if you intend to change the return value of the property Id.

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

, m.Id = 42, Get , Set.

mock.VerifySet(m => m.Id = 42);
+7

Source: https://habr.com/ru/post/1772743/


All Articles