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:
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?
@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.
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.
@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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With