Sometimes Typemock Isolator can be too powerful


A colleague made the comment regarding Typemock Isolator: “but be aware that having such a powerful mocking facility may reduce the effectiveness of your unit tests as design aids”.

I’ve used Typemock Isolator and it allows you to test your business logic even if it is poorly factored. For example, let’s say you have some legacy code that creates an instance of a dependant service using the “new” operator.

public class MyClass
{
    //Constructor
    public void MyClass()
    {
        this.dependantServiceA = new DependantServiceA();
        ...
    }
}

Typemock Isolator will allow you to mock out the call to the dependant service’s constructor. This is a really handy feature but should be used in conjunction with aggressively refactoring the code, passing in the dependant service through an interface instead of having a hard coded dependency on the concrete implementation.

public class MyClass
{
    //Constructor
    public void MyClass(IDepdantServiceA dependantServiceA)
    {
        this.dependantServiceA = dependantServiceA;
        ...
    }
}

If your code is being used in a framework that requires your class to have a default constructor, you can use a service locator to get access to dependant services.

public class MyClass
{
    //Constructor
    public void MyClass()
    {
        this.dependantServiceA = ServiceLocator.Get<IDependantServiceA>();
        ...
    }
}

The moral to this story is… Just because you can unit test your code with Typemock Isolator doesn’t mean that your code is well written and well factored.


Comments (2)

  1. Unit tests should not be design aids. Designing for tests does not necessarily give the best overall design. In particular, it often tends to overcomplicate things where a much simpler solution is otherwise sufficient.

  2. fcheung says:

    To me the biggest benefit of test driven development is that the design of the system starts with and is driven from how it is used. Unit tests demonstrate and articulate how the API should be used.

    I agree that this doesn’t guarantee the best overall design, but it usually results in an API that is easy to understand.