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?
Since static method belongs to the class, there is no way in Mockito to mock static methods. However, we can use PowerMock along with Mockito framework to mock static methods.
When writing tests in Groovy, the approach to mocking static calls will depend on the type of class you're testing and what type of class has the static method in. The CustomerTest Groovy class shows how the getType static method can be overridden using the metaClass property.
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).
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.
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