Very occassionally I need to mock a service that must do something more than just returning a value. Consider the contrived example of a Worker object that has a property called Count. During the execution of the function under test the Worker object is passed to an IIncrementer service to increment its Count property by one.
[Test]
public void DoStuffTest()
{
var incrementer = new Mock<IIncrementer>();
WOrker worker = new Worker(incrementer);
incrementer.Expect(i => Increment(worker));
worker.DoStuff();
Assert.AreEqual(1, worker.Count);
}
The test will fail because the IIncrementer mock didn't increment the count as expected. We can fake the required behaviour using Moq's Callback feature.
[Test]
public void DoStuffTest()
{
var incrementer = new Mock<IIncrementer>();
WOrker worker = new Worker(incrementer)
incrementer.Expect(i => Increment(worker)).Callback((Worker w) => w.Count+= 1);
worker.DoStuff();
Assert.AreEqual(1, worker.Count);
}
And now the test passes. This feature is extremely useful for services that do their work by changing the state of an object that is passed in, rather than returning a new object.