Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock with static methods?

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?

like image 365
brien Avatar asked Sep 30 '08 13:09

brien


People also ask

Can you mock a static method?

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.

How do I mock static methods in Groovy?

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.


2 Answers

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).

like image 90
Jon Skeet Avatar answered Oct 04 '22 11:10

Jon Skeet


I found a blog via google with some great examples on how to do this:

  1. Refactor class to be an instance class and implement an interface.

    You have already stated that you don't want to do this.

  2. Use a wrapper instance class with delegates for static classes members

    Doing this you can simulate a static interface via delegates.

  3. 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.

like image 22
Rick Minerich Avatar answered Oct 04 '22 13:10

Rick Minerich