Thursday, 10 September 2009

Principles of Acheiving Testable Software Design

Goal: Testable Software Design

Challenge 1: Unit testing a method which is using a static method or property of another class

Problem example:
public class Utils
{
public static int Add(int a, int b)
{
return a + b;
}
}

public int UnitTestMe(int a, int b)
{
return UnitTestMe(Utils.Add(a, b));
}

Solution 1: Overload your system under test method

Add this:

public int UnitTestMe(int r)
{
return r;
}


Challenge 2: Unit testing a method which is using an instance method or property of another class

Problem example:

public class Utils
{
public int Add(int a, int b)
{
return a + b;
}
}

public int UnitTestMe(int a, int b)
{
var utils = new Utils();
return utils.Add(a, b);
}

Solution 1: Inject the dependency

1. Create an interface of your dependent class:

public interface IUtils
{
int Add(int a, int b);
}

2. Let your dependent class implement the new interface:

public class Utils: IUtils
{
public int Add(int a, int b)
{
return a + b;
}
}

3. Inject the dependency to the class that the UnitTestMe method exists

IUtils utils = new Utils();
public MyClass(IUtils utils)
{
this.utils = utils;
}

4. Change the UnitTestMe method to use the injected dependency

public int UnitTestMe(int a, int b)
{
return utils.Add(a,b);
}

Challenge 3: How to unit test a method that uses ConfigurationManager

Solution:
Wrap the ConfigurationManager; see this.


More:

No comments: