How To Use MockitoExtension with Junit 5 (Jupiter)


#1

Junit5 is out with it’s exciting new features!

After seeing the new cool features of Junit5, we’d like to migrate our Junit4 tests to Junit5 for our Badges application. There aren’t many differences between the annotations. So migration is trivial, you can check that slide to grasp the idea how easy it is. I saw a guy’s post who migrated his 2K+ tests to Junit5 in only one day!

If you feel lazy you can leave your previous tests in Junit4 too. So, as you can understand, migration from Junit4 to Junit5 is not a big deal.

The only problem we faced during the migration was using Mockito with Junit5.

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest{

In Junit5 they left the RunWith idea behind and now we need to use ExtendWith annotation.

@ExtendWith(MockitoExtension.class)
public class ServiceTest{

There is an example implementation of mockitoExtension class by Junit5 developers. However, Mockito developers decided to not to implement it directly to their package. There are several reasons for it. One of them is they wanted to wait for JUnit developers to have a stable version of their package. The other one is when a developer started to implement a Mockito Extension package for them, he understood that he is violating the rule of Mockito developers: Don’t have any dependency to others. They left this issue and decided to implement it with Mockito3.0.

So what should you do?

If you’d like to use Junit5 but your project also dependent on Mockito and you don’t want to left it out there are two options for you:

Wait until Mockito’s 3rd version is released. Then you’ll have a chance to easily migrate your project.

Other option is to just create MockitoExtension class in your utils file and copy and paste the following code on it:

Now you can annotate your test classes with

@ExtendWith(MockitoExtension.class)
public class ServiceTest{