문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

Generally speaking it's really bad idea to do such hardcore stubbing (it's not mocking what you describe). I'd go with building tiny abstraction over this library so that you can have full control on what you want to return. It is possible to use some features of PowerMock outside tests but this not piece of cake. Here you have rough description that can help if you really want: https://groups.google.com/d/msg/powermock/SMDMe-y6fLg/1HF0TsGOqTIJ

Anyway I would not recommend doing that.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top