简体   繁体   中英

Setup Moq to increment value when method called

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

_myRepo.Save(somePoco);

_myRepo is mocked, eg:

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, eg:

myRepo.Setup(x => x.Save(It.IsAny<SomePoco>())
   .Callback(x => // how do i get the poco?);

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM