JUnit testing - ExtendWith
When to use @RunWith and when @ExtendWith
https://stackoverflow.com/questions/55276555/when-to-use-runwith-and-when-extendwith
-
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. If you are using JUnit 5, there’s no need to add the equivalent@ExtendWith(SpringExtension.class)as@SpringBootTestand the other@…Testannotationsare already annotated with it.
SpringRunner - https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/junit4/SpringRunner.html MockitoJUnitRunner - https://www.javadoc.io/doc/org.mockito/mockito-core/2.6.8/org/mockito/junit/MockitoJUnitRunner.html
Differences between them
Before Junit 5, the JUnit 4 version of the library used two types of components for extending a test: test runners and rules. By comparison, JUnit 5 simplifies the extension mechanism by introducing a single concept: the Extension API.
An important difference that was introduced with @ExtendWith is that it can receive an array of extensions allowing many of them to be used in the same test. Something like this, can be done
@ExtendWith({MockitoExtension.class, LogAsserterExtension.class})
class MyTest
With @RunWith back in JUnit 4, only one Runner class was allowed and you had problems when you want to use Mockito and Params on the test for example, because you couldn’t use MockitoJUnitRunner and JUnitParamsRunner at the same time.
ExtendWith
The purpose of Junit 5 extensions is to extend the behavior of test classes or methods, and these can be reused for multiple tests.
ExtendWith - https://junit.org/junit5/docs/5.8.0/api/org.junit.jupiter.api/org/junit/jupiter/api/extension/ExtendWith.html
Classes that work with @ExtendWith
OutputCaptureExtension- https://docs.spring.io/spring-boot/api/java/org/springframework/boot/test/system/package-summary.htmlSpringExtension- https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/junit/jupiter/SpringExtension.htmlMockitoExtension- https://www.javadoc.io/doc/org.mockito/mockito-junit-jupiter/2.25.1/org/mockito/junit/jupiter/MockitoExtension.html
Reading material
TODO
https://rieckpil.de/what-the-heck-is-the-springextension-used-for/