Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a Class with a Static Class/method dependency

So I have a class that looks like this:

public class MyClassToTest()
{
    MyStaticClass.DoSomethingThatIsBadForUnitTesting();
}

and a static class that looks like this:

public static class MyStaticClass()
{
    public static void DoSomethingThatIsBadForUnitTesting()
    {
        // Hit a database
        // call services
        // write to a file
        // Other things bad for unit testing
    }
}

(Obviously this is a dumbed down example)

So, I know that the second class is doomed when it comes to unit testing, but is there any way to uncouple the MyClassToTest class so that I can test it (WITHOUT instantiating MyStaticClass). Basically, I would want it to ignore this call.

Note: Sadly this is a Compact Framework Project, so tools like Moles and Typemock Isolator cannot be used :(.

like image 529
Vaccano Avatar asked Feb 03 '23 02:02

Vaccano


1 Answers

Define an interface that does the same thing as DoSomethingThatIsBadForUnitTesting, for instance:

public interface IAction {
    public void DoSomething();
}

(Obviously, in real code, you'd pick better names.)

Then you can write a simple wrapper for the class for use in production code:

public class Action : IAction {
    public void DoSomething() {
        MyStaticClass.DoSomethingThatIsBadForUnitTesting();
    }
}

In MyClassToTest, you pass in an instance of IAction via its constructor and call the method on that instance instead of the static class. In production code, you pass in the concrete class Action so the code behaves as before. In the unit test, you pass in a mock object that implements IAction, either using a mock framework or rolling your own mock.

like image 161
Michael Williamson Avatar answered Feb 05 '23 15:02

Michael Williamson