LINQ

Mocking with LINQ: Moq is here!

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!

Prime generator with LINQ

Maybe this example is not impressive as an entire ray tracer in a single line, but it gives an idea of the expressiveness of LINQ.

I remember from my high school times, the internal spontaneous competitions looking for the “fastest” prime generators. We were really far from the greatest and well known prime generators, but things like that one gave us funny ways to learn interesting stuff. The algorithm used in this post is a naïve version, that has nothing to do with “fast”.

Since C# 2.0, we can write custom enumerators very easily and create “generators” like this one:

IEnumerable PositiveIntegers
{
  get {
    for (int i = 1; ; i++)
      yield return i;
  }
}

Now with LINQ, is very easy to write lazy evaluated sequences like this one:

var primes = from n in PositiveIntegers.Skip(1)
             where
                 PositiveIntegers.Skip(1)
                     .TakeWhile(x => x <= Math.Sqrt(n))
                     .All(x => (n % x) > 0)
             select n;

or even using subqueries:

var primes = from n in PositiveIntegers.Skip(1)
             where
                 (from m in PositiveIntegers.TakeWhile(x => x <= Math.Sqrt(n))
                 where m >= 2 && (n % m) == 0
                 select m).FirstOrDefault() == 0
             select n;

Now you can assume that primes contains all the infinite series of primes! In fact it’s a lazy evaluated enumerator, that searches for the next prime every time you call the MoveNext method.

So, you can search the primes less that 100:

foreach (var x in primes.TakeWhile(n => n < 100))
    Console.WriteLine(x);

the first 100 primes:

foreach (var x in primes.Take(100))
    Console.WriteLine(x);

or look for the 200th prime:

var prime200 = primes.ElementAt(200);

Of course, don’t try to iterate the entire sequence ;-).