JUnit 5 Standard Test Class Basic Template

1. Overview

In this post, we will discuss the JUnit 5 standard basic template. This post also explains the basic usage of JUnit 5 annotations. The following templates are a good starting point.
Copy/paste and edit these templates to suit your coding style.
A test method is an instance method that is directly or meta-annotated with @Test, @RepeatedTest, @ParameterizedTest, @TestFactory, or @TestTemplate.
test class is any top-level or static member class that contains at least one test method.
List of Annotations available in JUnit 5:

2. A Standard Test Class and Methods

import static org.junit.jupiter.api.Assertions.fail;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

class StandardTests {

    @BeforeAll
    static void initAll() {
    }

    @BeforeEach
    void init() {
    }

    @Test
    void succeedingTest() {
    }

    @Test
    void failingTest() {
        fail("a failing test");
    }

    @Test
    @Disabled("for demonstration purposes")
    void skippedTest() {
        // not executed
    }

    @AfterEach
    void tearDown() {
    }

    @AfterAll
    static void tearDownAll() {
    }

}

3. Examples of Test Class and Test Methods

package com.javadevelopersguide.junit5;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

public class JUnit5Tests {

 @BeforeAll
 static void setup() {
  System.out.println("@BeforeAll executed");
 }

 @BeforeEach
 void setupThis() {
  System.out.println("@BeforeEach executed");
 }

 @Tag("DEV")
 @Test
 void testCalcOne() {
  System.out.println("======TEST ONE EXECUTED=======");
  Assertions.assertEquals(4, Calculator.add(2, 2));
 }

 @Tag("PROD")
 @Disabled
 @Test
 void testCalcTwo() {
  System.out.println("======TEST TWO EXECUTED=======");
  Assertions.assertEquals(6, Calculator.add(2, 4));
 }

 @AfterEach
 void tearThis() {
  System.out.println("@AfterEach executed");
 }

 @AfterAll
 static void tear() {
  System.out.println("@AfterAll executed");
 }
}

4. Conclusion

Comments