Search code examples
javatestingmockingpowermockproxy-classes

How to mock a static call on a class from a third-party library


I am wondering whether it is possible with PowerMock or any other library to mock out a static call in a class from a library. The class in that third-party library makes a call to one of the classes in the rt.jar and I want a return a custom implementation of that returned Type. I am trying to do this outside of test code.

Otherwise, I had to extend a few classes from that library and replace some implementation. Has someone done anything like this before?


Solution

  • Yes it is possible, e.g. using PowerMock.mockStatic() or PowerMock.mockStaticPartial() if you want to mock one method, only.

    There is a quite good tutorial on the homepage of PowerMock.

    I posted an example on SO.

    [EDIT] IF you want to do such magic in production code, however, I would recommend NOT to use a Testing-Framework. Maybe Groovy can help you with that - it is possible with Groovy to manipulate classes (even JDK classes) at runtime, and it is (I think) a thinner layer on top of the JVM.