When to use @RunWith and when @ExtendWith

Spring BootAnnotationsJunit4Junit5

Spring Boot Problem Overview


My team and I have been working on a bunch of microservices using Spring boot. Since the services went through JUnit and Spring Boot upgrades (We're using now Spring Boot 2 and JUnit 5), different JUnit implemented by different devs, are now using different patterns with:

  • @ExtendWith
  • @RunWith

Today what's the difference between the two of them and do we really need them for our Unit Tests or are embedded in some new Spring Boot annotation?

Spring Boot Solutions


Solution 1 - Spring Boot

If you are using Junit version < 5, so you have to use @RunWith(SpringRunner.class) or @RunWith(MockitoJUnitRunner.class) etc.

If you are using Junit version = 5, so you have to use @ExtendWith(SpringExtension.class) or @ExtendWith(MockitoExtension.class) etc.

  1. SpringRunner
  2. MockitoJUnitRunner
  3. SpringExtension
  4. MockitoExtension

Solution 2 - Spring Boot

The answer can be found in the documentation:

> If you are using JUnit 4, don’t forget to > add @RunWith(SpringRunner.class)to your test, otherwise the > annotations will be ignored. If you are using JUnit 5, there’s no need > to add the equivalent @ExtendWith(SpringExtension.class) as @SpringBootTest and the > other @…Testannotations are already annotated with it

.

Solution 3 - Spring Boot

@RunWith is an old annotation from JUnit 4 to use test runners. If you're using JUnit 5 (Jupiter), you should use @ExtendWith to use JUnit extensions.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAR1View Question on Stackoverflow
Solution 1 - Spring BootTinyOSView Answer on Stackoverflow
Solution 2 - Spring BootAR1View Answer on Stackoverflow
Solution 3 - Spring BootMureinikView Answer on Stackoverflow