Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should SpringRunner be used in Spring Boot with Junit 5

I am confused about the class SpringRunner. From Stackoverflow and google did understand that SpringRunner and SpringJunit4ClassRunner are one and the same.

@RunWith(SpringRunner.class)

My understanding of this class is :

  • that as its name implies - it is a 'runner' ( it will run the Junit tests )
  • This class is used while performing unit testing with the annotation @RunWith
  • This annotation helps in loading a spring application context and helps ‘autowire’ dependencies.
  • This class should only be used if we need spring context bean dependencies.
  • So this class should be used with caution otherwise we will unnecessarily load spring context during testing.
  • This class helps Junit and Spring collaborate together.

With Junit5 and spring boot is this class no longer required ?

If yes what should we be using in a spring boot and Junit5 environment then ?

like image 573
satish marathe Avatar asked Dec 12 '25 19:12

satish marathe


2 Answers

From the reference document

If you are using JUnit 4, don’t forget to also 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 @…Test annotations are already annotated with it.

like image 61
R.G Avatar answered Dec 15 '25 08:12

R.G


With Junit5 and spring boot is this class no longer required?

The annotation @RunWith(SpringRunner.class) is no longer required, you can delete it.

Additionally, if you use only Junit5, it is recommended to exclude Junit4:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
   <exclusions>
      <exclusion>
         <groupId>org.junit.vintage</groupId>
         <artifactId>junit-vintage-engine</artifactId>
      </exclusion>
   </exclusions>
</dependency>
like image 29
Marc Avatar answered Dec 15 '25 10:12

Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!