Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we now mock static methods with Mockito 2?

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?

like image 352
F.BOU Avatar asked Mar 20 '17 17:03

F.BOU


1 Answers

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.

like image 62
GhostCat Avatar answered Oct 11 '22 13:10

GhostCat