JUnit testing - ExtendWith

When to use @RunWith and when @ExtendWith

https://stackoverflow.com/questions/55276555/when-to-use-runwith-and-when-extendwith

  1. If you are using Junit version < 5, so you have to use @RunWith(SpringRunner.class) or @RunWith(MockitoJUnitRunner.class) etc.

  2. 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 @SpringBootTest and the other @…Testannotations are 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

  1. OutputCaptureExtension - https://docs.spring.io/spring-boot/api/java/org/springframework/boot/test/system/package-summary.html
  2. SpringExtension - https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/junit/jupiter/SpringExtension.html
  3. MockitoExtension - https://www.javadoc.io/doc/org.mockito/mockito-junit-jupiter/2.25.1/org/mockito/junit/jupiter/MockitoExtension.html

Reading material

  1. https://www.baeldung.com/junit-5-extensions
  2. https://www.lambdatest.com/blog/junit5-extensions/

TODO

https://rieckpil.de/what-the-heck-is-the-springextension-used-for/


Links to this note