Rhino Mocks 2.4 - More on DRY

time to read 7 min | 1201 words

As I said, I update the minor version number every time I add a big feature, this time it's all about DRY and .Net 2.0. From the start Rhino Mocks was capable of being used on the 2.0 framework, but its home was the 1.1. That caused some pain to me every single time that I had to write something like:

IDemo demo = (IDemo) mocks.CreateMock(typeof(IDemo));

Just count the number of times that I repeat the type of the mock object here, three times! This is stupid and it violate the DRY principal in a fairly big way. Unfortantely, there is no good way to resovle this issue on the 1.1 framework, but there is using the 2.0. Generics! {Excuse me while I sing the joy of no more custom collections}.

The goal was to reach this:

IDemo demo = mocks.CreateMock<IDemo>();

The first thing to do was to test Rhino Mocks in mocking a generic interface:

[Test]

public void MockAGenericInterface()

{

    using (MockRepository mocks = new MockRepository())

    {

        IList<int> list = mocks.CreateMock < IList<int> >();

        Assert.IsNotNull(list);

        Expect.Call(list.Count).Return(5);

        mocks.ReplayAll();

        Assert.AreEqual(5, list.Count);

    }

}

I run this test, and it passed! Did I mention that I dig DynamicProxy yet? I then started to clean up some warning about obsolete interfaces (no one wants to hear that their code is obsolete, right?) which I managed to do cleanly and easily, then I moved to take care of the collections. I've mentioned in the past that I've had problems with custom collections becoming too big (40% of the application code), so I was very eager to use them.

I had a problem with replacing a hash table with a Dictionary<T> because of the KeyNotFoundException, which I was aware of, but didn't really pay attention to. The tests made it really easy to pin point the problem (although 80+ failing tests did make my heart go THUD!), which was very easy to fix (and I was using the indexer in just one place, strange).

That done, I change MockRepository to a partial class, and put all the generic methods in a seperate file (I really like this, btw). That was merely a matter of adding a couple of T and typeof(T) in the right places and I was done. A couple of tests and I was done, .Net 2.0 & generics support!

One thing to note:

Rhino Mocks remains compatible with the 1.1 framework and will continue to do so for the foreseeable future!

Users of the 2.0 framework version would get a mocking framework that allows them to use generics to specify the mock objects, that internally uses the System.Collections.Generics and that is all.

The downloads are at the usual place and the API Documentation has been updated. I've yet to update the documentation itself, but I'll do it later today, I hope.