Juan Wajnerman

Juan Wajnerman

Mocking with LINQ: Moq is here!

3 min
Dec 19 2007
.NET, LINQ
3 min
Dec 19 2007

In these days of agile and TDD, most probably you had to deal with mocks. In such case, you have two options: create hundreds of mock classes by hand, one for each expected behavior for every unit test, or use a mock framework.

There are many mock frameworks available for .NET but all of them have one or both of the following problems:

  1. The framework rely on the member names as strings, making really difficult the refactoring sessions.
  2. The mock objects are created based on the interaction and sequences of calls.

The last problem is probably subjective, but I believe the unit tests should not rely on the interaction of the tested entity with the outside. Otherwise, these tests would be tightly coupled with the implementation making possible refactoring and optimizations almost impossible without rewriting the entire test suite.

So, how to solve these issues and what LINQ has to do with all this? Moq is the answer! And you can read the "official" announcement in the kzu's weblog. I've been working with him in this project as was completely amazing to have the first prototype working in just an hour of pairing and having written just a bunch of dozens of code lines! LINQ rocks! :)

Many examples are given in the project site, but I'll copy some of them so you can get excited:

var mock = new Mock<ICloneable>();
var clone = new object();

mock.Expect(x => x.Clone()).Returns(clone);

Assert.AreEqual(clone, mock.Instance.Clone());

I think the framework interface is self explanatory. Even for more complicated examples like this one with callbacks:

var mock = new Mock<IFoo>();
bool called = false;
mock.Expect(x => x.Do1()).Callback(() => called = true).Returns(1);

Assert.AreEqual(1, mock.Instance.Do1());
Assert.IsTrue(called);

Or even very flexible filters (powered by LINQ):

var mock = new Mock<IFoo>();

mock.Expect(x => x.Duplicate(It.Is<int>(value => value < 5 && value > 0))).Returns(() => 1);

Assert.AreEqual(1, mock.Instance.Duplicate(3));

Enjoy!