Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use @RunWith and when @ExtendWith

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?

like image 938
AR1 Avatar asked Mar 21 '19 08:03

AR1


People also ask

What is the use of @RunWith SpringRunner class?

@RunWith(SpringRunner. class) provides a bridge between Spring Boot test features and JUnit. Whenever we are using any Spring Boot testing features in our JUnit tests, this annotation will be required.

What is the use of @ExtendWith SpringExtension class?

When the test requires a Spring Test Context ( to autowire a bean / use of @MockBean ) along with JUnit 5's Jupiter programming model use @ExtendWith(SpringExtension. class) . This will support Mockito annotations as well through TestExecutionListeners.

What is the use of ExtendWith?

@ExtendWith is a repeatable annotation that is used to register extensions for the annotated test class, test interface, test method, parameter, or field. Annotated parameters are supported in test class constructors, in test methods, and in @BeforeAll , @AfterAll , @BeforeEach , and @AfterEach lifecycle methods.

What is the use of @RunWith in JUnit?

If a JUnit class or its parent class is annotated with @RunWith, JUnit framework invokes the specified class as a test runner instead of running the default runner. The specified 'value' element must be a subclass of the abstract org.


2 Answers

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
like image 200
TinyOS Avatar answered Oct 22 '22 03:10

TinyOS


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

.

like image 37
AR1 Avatar answered Oct 22 '22 05:10

AR1