How can I mock static methods in Java 1.4?

786 views Asked by At

I'm using JUnit with Mockito. PowerMock can mock static methods but it doesn't seem to be possible to use it with Java 1.4, specially since it needs annotations.

Is there any other alternative?

Thanks.

3

There are 3 answers

1
Pablo Grisafi On BEST ANSWER

(Shameless self promotion here) There is a project PowerMock-Legacy that lets you use PowerMock in Java 1.4. It is a bit verbose, and not all functionality is supported, but may worth a try.

1
Adam Crume On

Personally, I prefer minimizing my use of mocks. If the static method is in your code, I'd modify it to make it more unit test friendly. Maybe it shouldn't be static. Or if it has to be, maybe you could use a setup method that determines how the static method behaves.

If the static method is not in your code, you're probably out of luck.

1
Martin Dürrmeier On

Try jMockit and double check if you can refactor the code (or is it legacy code?). Mockito says about mocking static Methods

Mockito prefers object orientation and dependency injection over static, procedural code that is hard to understand & change. (Source)

Check also this related post especially Jon's answer.