Setting Moq to Increase a Value When Calling a Method

I have a POCO that I save, for example:

_myRepo.Save(somePoco); 

_myRepo ridiculed, for example:

 var myRepo = new Mock<IRepo>(); 

When this Save method is called, I want to set somePoco.Id to 1.

How can I do it?

I see that there is a Callback .Setup method, but it does not go through POCO, for example:

 myRepo.Setup(x => x.Save(It.IsAny<SomePoco>()) .Callback(x => // how do i get the poco?); 
+4
source share
1 answer

Parameters are passed to the Callback method, you just need to explicitly specify the types.

So the following should work:

 myRepo.Setup(x => x.Save(It.IsAny<SomePoco>())) .Callback<SomePoco>(poco => { poco.Id = 1; }); 

See also quick start examples:

 // access invocation arguments mock.Setup(foo => foo.Execute(It.IsAny<string>())) .Returns(true) .Callback((string s) => calls.Add(s)); 
+8
source

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


All Articles