Issue
I wanted to replace my JUnitRunner by Powermockrunnner (in order to further use features of Powermock that simple Mockito does not have).
So I added the dependencies, replaced the runner in my test class, and added the @PrepareForTest annotation and, before writing any further test code, ran my existing tests to validate them.
Of ~25 tests, 5 or 6 failed with apparently functional reasons (I mean they failed on actual failures in the run code, not on some infrastructural errors).
In a normal state, these tests are 100% consistent and non-flaky.
How can such a change fail fully working tests?
Solution
In order to help you diagnosing your problems, you would have to post some of your failing tests.
But honestly; you are going down the wrong rabbit hole here!
The only two features that PowerMock(ito) offers over Mockito are: it can mock static calls and calls to new().
The prize you pay for those features:
- Backlevel versions of Mockito are forced on you. Mockito itself is at version 2.8 right now; but PowerMockito doesnt't work with anything newer than Mockito 2.0.40 beta something (and the Mockito team does releases on an almost weekly basis!)
- PowerMock relies on bytecode manipulation. Meaning: mocking static calls changes your production code. Yes, all of that works. But just have a look at all the questions here tagged PowerMock - you might notice a pattern. There are quite some questions about obscure problems, that most often go unanswered. And as soon as you start using other JVMs than Oracle ... "fun" is guaranteed. (Believe me, been there!)
- PowerMock doesn't go nicely with other frameworks that require byte code manipulation, for example EcLemma for coverage measurements.
Beyond that: your need to use PowerMock doesn't come out of the blue. It is based on the fact that you created hard-to-test code.
Thus my suggestion: learn how to write easy-to-test code (by watching these videos for example) instead. The core aspect there: easy-to-test code is most likely also better designed. static leads to tight coupling, and it breaks polymorphism, the essence of OO.
So, my advise: upgrade to the latest version of Mockito; instead of spending time to learn about a framework that A) has caused a lot of pain in the past B) encourages you to not fix broken designs, but work around them.
2 cent of personal experience: our team was using PowerMock when we started unit testing. We spent countless hours looking at some of those bizarre PowerMock problems. In the end: we learned how to write better production code; and we learned how to properly test them with Mockito. We are not using PowerMock any more; and we have never regretted that decision.
Answered By - GhostCat