I have been reading Art of Unit Testing by Roy Osherove. He talks about a strategy he calls Extract & Override. It is a way to break dependencies in order to make class more testable. Let’s look at a simple example:
public class Class
{
public int DoCalculation(int number)
{
var value=Singleton.Instance.GetValue();
return number + value;
}
}
Not many lines of code, but still essentially un-unit testable. One might be able to test it quite pain free, if Singleton dependency is simple enough. Oftentimes this is not the case. Often it can be some resource that is difficult or impossible to access while running tests, such as a database, web service or a physical device.
Here is the same class with dependency extracted into a factory method.
public class TestableClass
{
public int DoCalculation(int number)
{
var value = FactoryMethod();
return number + value;
}
protected virtual int FactoryMethod()
{
return Singleton.Instance.GetValue();
}
}
This allows unit testing with the help of inheritance.
[Test]
public void TestInheritedClass()
{
TestableClass classToTest = new InheritedTestableClass();
Assert.AreEqual(3, classToTest.DoCalculation(2));
}
class InheritedTestableClass:TestableClass
{
protected override int FactoryMethod()
{
return 1;
}
}
Inheriting the class under test allows overriding the factory method and stubbing its return value.
Extract & override strategy can be useful when working with legacy or brownfield codebase. It makes it easier to bring highly coupled code into testable state. One might eventually refactor dependencies to be hooked up via costructor- or property injection, but it can be easier to set to that path if you already tests to cover your back.
Software professional with a passion for quality. Likes TDD and working in agile teams. Has worked with wide-range of technologies, backend and frontend, from C++ to Javascript. Currently very interested in functional programming.