DEV Community

Cover image for JUnit 5
Anne Quinkenstein
Anne Quinkenstein

Posted on • Updated on

JUnit 5

1. Do a Maven Project

2. Change pom.xml

Search for lastest JUnit-Jupiter (Aggregator) in Maven(Aggregator downloads every dependencies )

Enter fullscreen mode Exit fullscreen mode

Change Configuration of the Maven Plugin to JDK8 and higher (required Java Version)

Enter fullscreen mode Exit fullscreen mode

3. Write Tests

any class that contains at least one test method is considered a test class.
access Modifier should NOT be private
return Type is always void

package junit5tests;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

public class firstTest {

    void firstMethod() {
        System.out.println("This is the first test method");

    @DisplayName("US1234 - TC12 - this method is the second one")
    void secondMethod() {
        System.out.println("This is the second test method");
Enter fullscreen mode Exit fullscreen mode

4. Lifecycle Methods

There are @BeforeAll Annotations for Setting up something before the Tests and @BeforeEach to set up before each Testcase. Cleaning up is done with @AfterAll, @AfterEach Methods.

    void beforeAll() {
        System.out.println("--This is the before All method");

    void beforeEach() {
        System.out.println("----This is the before Each method");

    void afterAll() {
        System.out.println("--This is the after All method");

    void afterEach() {
        System.out.println("----This is the after Each method");
Enter fullscreen mode Exit fullscreen mode

6. Parameterize Test

6.1. constant values or literals

instead of @test annotation -> @ParameterizedTest
@ValueSource annotation to pass (just) ONE Value -> use an Array e.g. int[] or String[]
it will run throught the array and pass each parameter to the method -> so the methods takes one param of the type of the Array. e.g. void intValues (int theParam)
(we have to pass the values, cant pass methods that generates the value)

to beautify it, add round brakets to PramiterizesTests + add Tests with w.g. {index} No of Runs and {arguments} the value of the Param used.

pass an Empty String: @EmptySource
pass a null value: @NullSource
pass both: @NullAndEmptySource

public class ParamiterizedTests {

    @ParameterizedTest(name = "Run: {index} - value: {arguments}")
    @ValueSource(ints = {1,5,6})
    void intValues(int theParam) {
        System.out.println("theParam = " + theParam);

    @ParameterizedTest(name = "Which Run? {index} - What did we use? {arguments}")
//  @EmptySource
//  @NullSource
    @ValueSource(strings = {"firstString", "secondString"})
    void stringValues(String theParam) {
        System.out.println("theParam = " + theParam);


Enter fullscreen mode Exit fullscreen mode

Top comments (0)