Upgrading yourself from Junit 4 to Junit 5
What is new in Junit5 as compare to Junit4
- Junit4 framework was contained in a single jar library. The whole library needs to be imported even when only a particular feature is required. In JUnit 5, we get more granularity and can import only what is necessary
- One test runner can only execute tests in JUnit 4 at a time . JUnit 5 allows multiple runners to work simultaneously
- JUnit 4 never advanced beyond Java 7, missing out on a lot of features from Java 8. JUnit 5 makes good use of Java 8 features
Package/modules of Junit 5
- Jupiter contains all the junit 5 api
- vintage allows backward compatibility with JUnit 4 or even JUnit 3
New annotations of Junit5
@DisplayName
@DisplayName
is used to declare a custom display name for the annotated test class or test method.
@Disabled
@Disabled
is used to signal that the annotated test class or test method is currently disabled and should not be executed.
@BeforeEach & @AfterEach
Annotations for running code before and after each method
@BeforeAll & @AfterAll
Annotations for running code before and after each class
By default the methods need to be static
in both JUnit 4 and 5, but in v5 we can annotate the class to avoid need to make the All
methods static:
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
Exception Handling in junit-5
JUnit 5 uses an assertion with the code in a closure lambda expression, which allows additional assertions to be made on the exception
Conditional Execution
@EnabledOnOS(OS.Linux) & @EnabledOnJre(JRE)
assumeTrue & assumeFalse
assumeTrue() validates the given assumption to true and if assumption is true — test proceed, otherwise test execution is aborted.
@assertAll
This assertion allows the creation of grouped assertions, where all the assertions are executed and their failures are reported together. In details, this assertion accepts a heading, that will be included in the message string for the MultipleFailureError
@Nested
@Nested helps to create hierarchical contexts to structure the related unit tests together; in short, it helps to keep the tests clean and readable.
@Tag
tags can be used to filter test discovery and execution of specific tests.