How to mock static methods with mockito?

2019-07-03 22:05发布

问题:

I am using mockito for the Junits

I know mockito donot mock static methods but is there a way around for this instead of using powermock?

Thanks

回答1:

Possible workaround would be to encapsulate static methods in real instance I think. Or real instance behind the static method.

Though that would mean you'll have to modify your production code.

Honestly if you ask yourself this question now, you are testing your code too late in the development process. (Now evangelizing ;)) If you were practicing TDD, you would have noticed this issue early, and tweaked your design early to be fully testable with classic testing software.

I personally use the "pain metrics" when practicing TDD to see if my design is ok or not. Of course everything depends on the context, but usually this is a good indicator of good design (at least for me and some others).

So my advice get rid of these static methods or revise your design to not be dependent on static method mocking.

Cheers



回答2:

Not sure what "way around" you are looking for. A lot of people use both Mockito and Powermock together and I've not heard any horror-stories about incompatibilities or conflicts. Just use Powermock in those instances where you need to mock static methods and you should be ok.

Or refactor to not use static methods in a way that requires mocking.



回答3:

No i think there isn't any way to do this withour PowerMock.

But you could break the dependency on this static methods, by introducing an adapter.