Test your code

Mockito 2

As Junit 5 was released in order to be able to use mocks you need to add the mockito extension. You noticed that ClassRunners are deprecated now in Junit 5, they were replaced with extensions, hence the Mockito Extension. What changes are in Mockito 2?

Well one of the most important one is the change of the mock engine from CGLIB to ByteBuddy. This change fixed some existing bugs, but more importantly it contributed to develop faster the changes needed for Java 8 and 9. Another change is they removed the hamcrest dependency (like Junit 5).

One cool feature is the ability to detect unused stubs. This is a great tool of improving your tests and eliminate unused stubs (verify them instead).

Screen Shot 2018-01-06 at 22.38.09

To be honest this did not work with the Junit 5 Mockito extension, maybe there is a bug there.

Similar to Junit 5, lazy verification of assertions is now possible using the VerificationCollector Rule. I won’t go into details since @Rule is not encouraged in Junit 5 and this feature is already there.

Another thing is the ability to mock final classes and methods, but this is an optional feature, still in development. If you are familiar with PowerMock you are surely wondering why they did this and PowerMock already has this. My feeling is that they want to give you the ability to write cleaner tests. Final classes are present usually in your code (they are a sign of good code), and sometimes you removed the final modifier just to be able to mock the class, giving up the advantage that final modifier gave you. You don’t need PowerMock for this anymore. I feel that using PowerMock is a little bit cheating, you simply have too much power and sometimes you tend to take shortcuts.

It can be activated via the mockito extension mechanism by creating the file

src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker

containing a single line:

mock-maker-inline

Mockito will pick up this and give you the possibility to mock final. This is not a nice way to activate it but it is still work in progress and surely it will get better. In a nutshell this are the most important changes to date.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.