Catching up on assorted geek blogs today I came across a mention of the MoQ library being used for unit testing in the Microsoft MVC development initiative that was updated recently.

Always interested in things that very clever people are talking about I grabbed some source to see how it’s used. It’s an amazing display of simplicity and brilliance.

So here’s a contrived example of an ICruncher object you may want to mock. In a unit test you may be testing something that uses the cruncher, like a widget, but you don’t want to instantiate and initialize an actual cruncher. There are lots of reasons for that – maybe the actual implementation modifies data or runs off a larger system that’s not conveniently available. Or maybe you simply want to test only the widget and don’t want any bugs in the cruncher to show up as failed widget tests.

In any case what you want is a mock implementation of ICruncher which will always act in a specific way that you can pass to the widget object you’re testing.

Here’s an example of using moq to make such a thing. It’s really a remarkable thing.


var cruncher = new Mock<ICruncher>();
cruncher.Expect(x => x.Add(2, 4)).Returns(6);
cruncher.Expect(yyy => yyy.Add(5, 2)).Returns(3);

int twoPlusFour = cruncher.Object.Add(2, 4);
int fivePlusTwo = cruncher.Object.Add(5, 2);

Console.WriteLine("twoPlusFour = {0}, fivePlusTwo = {1}", twoPlusFour, fivePlusTwo);

The cruncher’s “Object” property is of type ICruncher, and can now be passed to any widget being tested. There are a million ways to accomplish this of course, but what’s nice here is what little effort is needed to put this together. Less effort, greater efficiency, and probably more effective tests because it’s helping you fall into good tdd habits.