Solved in the comments:
after adding my test class in side @PrepareForTest, it works as expected
In short, Mockito writes a generated subclass for the class you're trying to mock, which allows it to intercept the behavior of overridable methods (i.e. non-final instance methods). This handles all interfaces and most abstract and concrete classes. However, if you're trying to mock the behavior of final
or static
methods, including constructors, there's nothing Mockito can do1: the consuming class contains a reference to the exact real implementation without a lookup to the virtual method table. The only way out is to rewrite and replace the bytecode of an existing class, which is exactly what PowerMock does.
It can often just overwrite the class you're trying to mock, but in certain circumstances you need to list the class under test or the test class itself.
Consequently, almost all tests that exercise PowerMock's features require a @PrepareForTest
, as well as a @RunWith
statement that ensures that the test class uses PowerMock's classloader to enable that rewriting.
1 since Mockito 2.1, Mockito can use instrumented classloaders to do some of the things that were previously only available in PowerMock.