satish marathe
satish marathe

Reputation: 1133

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 :

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 ?

Upvotes: 16

Views: 12618

Answers (3)

Hantsy
Hantsy

Reputation: 9261

@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.

Upvotes: 5

Marc
Marc

Reputation: 3245

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>

Upvotes: 8

R.G
R.G

Reputation: 7131

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.

Upvotes: 17

Related Questions