16

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 ?

3 Answers 3

17

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.

8

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>
5

@RunWith is a JUnit4 API.

In JUnit 5, use @ExtendedWith instead. Spring core provides a new SpringExtension for it. And there are some more flexible annotation available, eg. SpringJunitConfig

@SpringJunitConfig(classes= config classes)
public class ASpringTest
{}

For the usage of SpringJunitConfig, check more examples from here.

In the latest Spring Boot 2.4, JUnit 5 is the default test runner, use @SpringBootTest is enough, and Spring Boot also provide test slice capabilities for Spring Data, check my example here.

1
  • 2
    note: it's SpringJUnitConfig (capital U) from package org.springframework.test.context.junit.jupiter
    – Lennonry
    Commented Nov 23, 2021 at 11:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.