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 :(.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With