Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write mocks that capture method parameters and examine them later?

Tags:

.net

mocking

I'm looking for a way to capture the actual parameter passed to method to examine it later. The idea being to get the passed parameter and then execute assertions against it.

For instance:

var foo = Mock<Foo>();
var service = Mock<IService>();
service.Expect(s => s.Create(foo));
service.Create(new Foo { Currency = "USD" });
Assert(foo.Object.Currency == "USD");

Or a bit more complex example:

Foo foo = new Foo { Title = "...", Description = "..." };
var bar = Mock.NewHook<Bar>();
var service = new Mock<IService>();
service.Expect(s => s.Create(bar));

new Controller(service.Object).Create(foo);

Assert(foo.Title == bar.Object.Title);
Assert(foo.Description == bar.Object.Description);
like image 690
alex2k8 Avatar asked Sep 03 '09 19:09

alex2k8


1 Answers

I think you're looking for something equivalent to Moq's Callback:

var foo = Mock<Foo>();
var service = Mock<IService>();
service.Setup(s => s.Create(foo.Object)).Callback((T foo) => Assert.AreEqual("USD", foo.Currency))
service.Object.Create(new Foo { Currency = "USD" });
like image 161
Blake Pettersson Avatar answered Nov 19 '22 22:11

Blake Pettersson