Skip to content

Introduction

JUnit is the most popular tool used for creating unit tests for software written in Java.

Tests are usually placed in the path src/java/test. The test class should be called NameOfTheClassTest.java For example, if in our application, in the package pl.sdacademy.calculations, there is a class Calculator.java, then the test class should be called CalculatorTest.java and it also should be placed (although it's not necessary) in the package with the same name, ie. pl.sdacademy.calculations.

Dependencies

In order to use Junit library in tests, we have to add the following dependency to a Maven-based project, in pom.xmlfile in section dependencies:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.6.2</version> <!-- dostępna może być nowsza wersja -->
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.6.2</version>
    <scope>test</scope>
</dependency>

NOTE: The versions of the above dependencies`should be the same.

Test structure

For our sample class Calculator:

package pl.sdacademy.calculations;

public class Calculator {

    public double add(double first, double second) {
        return first + second;
    }
}

Example of a simple test written with JUnit can look as follows:

package pl.sdacademy.calculations;

import org.junit.jupiter.api.Test;

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

class CalculatorTest {

    @Test
    void shouldAddTwoNumbers() {
        // given
        double valueA = 5.2;
        double valueB = 3.1;
        Calculator calculator = new Calculator();

        // when
        double actualResult = calculator.add(valueA, valueB);

        //then
        assertEquals(8.3, actualResult);
    }
}

While looking at the example above we can notice, that:

  • a test is a method with any name, to which we have to add he reference Test
  • a test does not return anythin (we use the keyword void)
  • a test, unless it's not parametrized, does not contain any input arguments
  • a test always tests only one case
  • a test consists of three sections, which are usually separated with empty lines. These sections are:
    • given, in which we define the preconditions of the test (ie. we prepare all required objects)
    • when, which usually consists of one line - call of the test method
    • then, in which we use the so-called. assertions, which verify the expected results with the actual ones.

NOTE: Test classes, methods representing the tests and methods of test lifecycle can have any access modifier, but it's usually skipped (ie. package-private is used).

Running the tests

The created tests can be run in a few ways. Usually while writing the code, our test can be run directly from our IDE. If our project is based on Maven, then our tests can be ran in the test phase with the command mvn clean install.