Reputation: 337
I read that Mockito 2 doesn't use CGLIB/proxy any more but instead uses ByteBuddy for mock creation. Does that mean that from now on it is possible to mock static methods and private methods?
Upvotes: 8
Views: 17324
Reputation: 9446
I wrote an extension of Mockito 2
which uses AspectJ
to allow mocking
even things like static/private/final methods
, with one easy lambda-based syntax, for example:
when(() -> YourClass.staticMethodToCall(...)).thenReturn(...)
Upvotes: -2
Reputation: 140623
No, you can't (see their documentation here; I am sure they would mention that).
So, PowerMock(ito) and JMockit are the two mocking frameworks that support mocking static methods.
But, some personal opinion: one should nonetheless prefer to use Mockito instead PowerMock(ito); simply by writing code that can be tested with Mockito; and that doesn't need PowerMock. What I mean is: when you write your own code and you think you need to mock static calls; then you are writing hard to test code.
The answer is not to look to powerful mocking frameworks; but to write easy to test code instead. You can have a look into these videos to learn how to do that.
Finally: don't think that PowerMockito is a good alternative. Mockito is right now at version 2.79 (as of March 2017). But when you have a look at PowerMockito; you will find that it ships with some Mockito 2.0.42 beta something - because the PowerMockito folks can't get their tool working with any newer version of Mockito. And that is a shame, because those newer Mockito versions have a lot of interesting features.
Upvotes: 8