Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setup Moq to increment value when method called

I've got a POCO which im saving, like this:

_myRepo.Save(somePoco);

_myRepo is mocked, e.g:

var myRepo = new Mock<IRepo>();

When that Save method is called, i want to set somePoco.Id to 1.

How do i do it?

I see there is a Callback method on the .Setup, but it doesn't pass through the POCO, e.g:

myRepo.Setup(x => x.Save(It.IsAny<SomePoco>())
   .Callback(x => // how do i get the poco?);
like image 458
RPM1984 Avatar asked Dec 26 '22 03:12

RPM1984


1 Answers

The parameters get passed to the Callback method you just need to specify the types explicitly.

So the following should work:

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

See also the samples in the quick start:

// access invocation arguments
mock.Setup(foo => foo.Execute(It.IsAny<string>()))
    .Returns(true)
    .Callback((string s) => calls.Add(s));
like image 73
nemesv Avatar answered Dec 29 '22 10:12

nemesv