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:
- http://www.codeproject.com/Articles/35881/Simplified-Mocking-with-Dependency-Injection-for-U.aspx
- http://www.cs.colostate.edu/~rta/publications/ootestability.pdf
- http://swerl.tudelft.nl/twiki/pub/Main/PastAndCurrentMScProjects/emmanuel_mulo_thesis.pdf
- http://msdn.microsoft.com/en-us/magazine/dd263069.aspx
- http://freedft.info/
No comments:
Post a Comment