You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 18 Next »

This page describes how we can write our first test class with JUnit 5. After we have finished this blog post, we:

  • Can create test classes with JUnit 5.
  • Know how we can use setup and teardown methods.
  • Understand how we can write simple test methods with JUnit 5.

Let's start by creating our first simple test class.


1. Setup and Teardown methods

A test class can have four setup and teardown methods that must fulfill these two conditions:

  • These methods must not return anything. In other words, their return type must be void.
  • Setup and teardown methods cannot be private.

The supported setup and teardown methods are described in the following:

  • The method that is annotated with the @BeforeAll annotation must be static, and it's run once before any test method is run.
  • The method that is annotated with the @BeforeEach is invoked before each test method.
  • The method that is annotated with the @AfterEach annotation is invoked after each test method.
  • The method that is annotated with the @AfterAll annotation must be static, and it's run once after all test methods have been run.


Let's add these methods to our test class. After we have added these setup and teardown methods to our test class, its source looks as follows:

import org.junit.jupiter.api.*;
 
@DisplayName("JUnit 5 Example")
class JUnit5ExampleTest {
 
    @BeforeAll
    static void beforeAll() {
        System.out.println("Before all test methods");
//        Some examples of common expensive operations are:
//       - the creation of a database connection
//       - the startup of a server.     }
 
    @BeforeEach
    void beforeEach() {
        System.out.println("Before each test method");
//        This is useful when we want to execute some common code before running a test.
//        - list initialization
     }
 
    @AfterEach
    void afterEach() {
        System.out.println("After each test method");
    }
 
    @AfterAll
    static void afterAll() {
        System.out.println("After all test methods");
    }
}


After we have added setup and teardown methods to our test class, we can finally write our first test methods. Let's find out how we can do it.


2. Writing Our First Test Methods


Let's add two test methods to our test class:

The firstTest() method and secondTest() method have a custom display name and they write a unique string to System.out.


import org.junit.jupiter.api.*;

@DisplayName("JUnit 5 Overview class")
class JUnit5OverviewTest {

//    Setup
    @BeforeAll
    static void beforeAll() {
        System.out.println("\nBefore all test methods \n");
//        Some examples of common expensive operations are:
//       - the creation of a database connection
//       - the startup of a server.
    }

    @BeforeEach
    void beforeEach() {
        System.out.println("  Before each test method");
//        This is useful when we want to execute some common code before running a test.
//        - list initialization
    }

//    Teardown
    @AfterEach
    void afterEach() {
        System.out.println("  After each test method \n");
    }

    @AfterAll
    static void afterAll() {
        System.out.println("After all test methods\n");
    }

    @DisplayName("First test")
    @Test
    void firstTest() {
        System.out.println("    First test method");
    }

    @Test
    @DisplayName("Second test")
    void secondTest() {
        System.out.println("    Second test method");
    }


}


We have just written our first test methods. Let's see what happens when we run our unit tests.

3. Running tests

3.1. From shell

Remember to install Maven & Java 8!


Go to your project directory 

> cd TDD-java/Overview


and then run this:

> mvn clean test

// clean deletes caches


You shoud see sth like this this:

> mvn clean test  
              
[INFO] Scanning for projects...
[INFO] 
[INFO] --------------------< org.example:JUnit5_Overview >---------------------
[INFO] Building JUnit5_Overview 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ JUnit5_Overview ---
[INFO] Deleting /home/agatafilipczak/workspace/ACH/ach-tutorials/TDD-java/Overview/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ JUnit5_Overview ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ JUnit5_Overview ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 1 source file to /home/agatafilipczak/workspace/ACH/ach-tutorials/TDD-java/Overview/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ JUnit5_Overview ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/agatafilipczak/workspace/ACH/ach-tutorials/TDD-java/Overview/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ JUnit5_Overview ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 2 source files to /home/agatafilipczak/workspace/ACH/ach-tutorials/TDD-java/Overview/target/test-classes
[INFO] 
[INFO] --- maven-surefire-plugin:3.0.0-M1:test (default-test) @ JUnit5_Overview ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running JUnit5OverviewTest

// This is our output of tests

Before all test methods 

  Before each test method
    First test method
  After each test method 

  Before each test method
    Second test method
  After each test method 

After all test methods

// This is our results info about execution of tests

[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.06 s - in JUnit5OverviewTest
[INFO] Running ExampleTest
example test method
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 s - in ExampleTest
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.034 s
[INFO] Finished at: 2021-10-20T20:01:11+02:00
[INFO] ------------------------------------------------------------------------


3.2. From Intellij IDE

After we have set up the code for the testing, we can run the tests and find out if the tested methods are working correctly.

  • To run all tests in a test class, click Icons run configurations test state run against the test class declaration and select Run.

  • To run an individual test, click Icons run configurations test state run in the gutter and select Run.


You can view test results in the Run tool window at the bottom of IDE.


This output proves that the setup, teardown, and test methods are run in the correct order. Let's summarize what we learned from this blog post.

4. Summary

This tutorial has taught us four things:

  • A test class is a normal Java class that is either public or package private.
  • Setup and teardown methods must not be private and they must not return anything.
  • A test method is a method that isn't private and doesn't return anything.
  • We could specify the display name of a test class and a test method because this allows us to replace technical names with sentences that make sense.
  • No labels