TDD - Pattern: Factory Hides test interface

Here's a Test-First. pattern that I use a lot (and that I have seen others use), but not seen documented anywhere.

Factory Hides test interface

Context: You wish to write tests for a class that will need external information (i.e. externally dependent information) to create it.

Solution: Construct the object directly in your tests providing a faked version of the data and, then use a Factory to control creation by production code. In the factory (and only in the factory) access the external data. Your tests can then directly manipulate construction (e.g. by using a mock, or sample data) and your production code will have access to the real data.

Example:

public class Foo
{
    public static Foo Create()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("path to external file");
        //...
        return new Foo(doc.FirstChild);
    }

    protected Foo(XmlNode node)
    {
        //...
    }
}

public class FooTest : Foo
{
    public void SampleTest()
    {
        XmlNode node = new XmlNode();
        //set up node to look like real one
        //...
        Foo foo = new Foo(node);
        //rest of test
    }
}

This code also uses a variation of the Self-Shunt pattern because the test class is a subtype of the class to be tested.

A couple of other things to note: Often the Factory is left untested. If this code itself is complicated enough to need to be dealt with, then you may still need to do some external access from the tests, but at least you only have to do this once, for that code. Alternately, the Factory can create a separate object to this work, which you can then test separately (and take the external dependency hit independent of trying to test Foo).

Often the factory is written last (This itself is a pattern, that I will write up when I have a chance).