I'm new to mock objects, but I understand that I need to have my classes implement interfaces in order to mock them.
The problem I'm having is that in my data access layer, I want to have static methods, but I can't put a static method in an interface.
What's the best way around this? Should I just use instance methods (which seems wrong) or is there another solution?
A simple solution is to allow to change the static class's implementation via a setter:
So in the setup of your tests, you call
overrideImplementation
with some mocked interface. The benefit is that you don't need to change clients of your static class. The downside is that you probably will have a little duplicated code, because you'll have to repeat the methods of the static class and it's implementation. But some times the static methods can use a ligther interface which provide base funcionality.You might be trying to test at too deep a starting point. A test does not need to be created to test each and every method individually; private and static methods should be tested by calling the public methods that then call the private and static ones in turn.
So lets say your code is like this:
You do not need to write a test against the TransformData method (and you can't). Instead write a test for the GetData method that tests the work done in TransformData.
I found a blog via google with some great examples on how to do this:
Refactor class to be an instance class and implement an interface.
You have already stated that you don't want to do this.
Use a wrapper instance class with delegates for static classes members
Doing this you can simulate a static interface via delegates.
Use a wrapper instance class with protected members which call the static class
This is probably the easiest to mock/manage without refactoring as it can just be inherited from and extended.
Use instance methods where possible.
Use public static Func[T, U] (static function references that can be substituted for mock functions) where instance methods are not possible.
The problem you have is when you're using 3rd party code and it's called from one of your methods. What we ended up doing is wrapping it in an object, and calling passing it in with dep inj, and then your unit test can mock 3rd party static method call the setter with it.
Yes, you use instance methods. Static methods basically say, "There is one way to accomplish this functionality - it's not polymorphic." Mocking relies on polymorphism.
Now, if your static methods logically don't care about what implementation you're using, they might be able to take the interfaces as parameters, or perhaps work without interacting with state at all - but otherwise you should be using instances (and probably dependency injection to wire everything together).