The magic of AutoMocks - addendum

I just found a slight bug from the TestBase class in my post from earlier this week. I've updated the code in the post but thought I'd explain it here. The original class looked like this.

public class TestBase<T>
{
    private readonly IKernel _kernel;
    protected T Target;

    public TestBase()
    {
        _kernel = new RhinoMocksMockingKernel();
        Target = _kernel.Get<T>();
    }

    protected TDependency GetDependencyOf<TDependency>()
    {
        return _kernel.Get<TDependency>();
    }
}

The problem here is that the RhinoMocksMockingKernel is created in the constructor of the class. This isn't a problem if you're using xUnit as SetUp attribute was removed in favour of constructors and a new instance of the class is created for every test you run. This is also the case if you're using MSUnit. Unfortunately if you're using NUnit, as I obviously was in the example, a single fixture (or instance of the class) is created to run all your tests. I won't go into whether this was a good design choice as James Newkirk expresses his views in this post. Unfortunately because of this any expectations on mocks that you set up in one test can have a knock on effect on other tests. That's the reason that I've updated the code in the last post to read as follows.

public class TestBase<T>
{
    private IKernel _kernel;
    protected T Target;

    [SetUp]
    public void TestBaseSetUp()
    {
        _kernel = new RhinoMocksMockingKernel();
        Target = _kernel.Get<T>();
    }

    protected TDependency GetDependencyOf<TDependency>()
    {
        return _kernel.Get<TDependency>();
    }
}

We get round the problem by setting up the RhinoMocksMockingKernel in the SetUp method which is called before the test case is run. This means that the tests act in isolation which your unit tests always should.