Wednesday, 23 December 2009

Coding a class so that a dependancy can be easily injected when the class is tested

This is one example of how Dependancy Injection can be used so a dependancy can be mocked whilst the class is tested

public interface IDependancy { }

public class SomeDependancy : IDependancy {}

public class MockDependancy : IDependancy {}

public class SomeClass
{
    private IDependancy dependancy = null;

    public SomeClass()
        : this(new SomeDependancy())
    {
        //  Do some stuff
    }

    // for testing only
    private SomeClass(IDependancy dependancy)
    {
        this.dependancy = dependancy;
    }
}

public class TestSomeClass
{
    public void Test()
    {
        Type t = Assembly.Load(assemblyFullName).GetType(typeName);

        ConstructorInfo ci = t.GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(IDependancy) }, null);

        SomeClass c = (SomeClass)ci.Invoke(new object[] { new MockDependancy() });
           
        // test

    }
}


No comments: