Java automated test implementation with JUnit 5 + Apache Maven

Overview

--Write a basic sample of Java automated testing with JUnit 5 + Apache Maven

This environment

Basic sample of JUnit 5 + Apache Maven

Source code list

├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── myapp
    │           └── Calc.java
    └── test
        └── java
            └── myapp
                └── CalcTest.java

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>mygroup</groupId>
  <artifactId>myapp</artifactId>
  <packaging>jar</packaging>
  <version>1.0.0</version>
  <name>myapp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>

  <build>
    <plugins>
      <!--Introduced the plugin required for test execution in JUnit 5-->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M5</version>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <!--Introduced the library required for writing test code-->
    <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>5.7.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

reference:

Calc.java

package myapp;

public class Calc {

  private int base;

  //Set a reference value
  public Calc(int base) {
    this.base = base;
  }

  //Add
  public int plus(int num) {
    return base + num;
  }

  //Pull
  public int minus(int num) {
    return base - num;
  }
}

CalcTest.java

package myapp;

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.Test;

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

class CalcTest {

  //Run only once before the test starts
  @BeforeAll
  static void beforeAll() {
    System.out.println("Start CalcTest");
  }

  //Run only once after the test starts
  @AfterAll
  static void afterAll() {
    System.out.println("CalcTest finished");
  }

  //Executed before each test method starts
  @BeforeEach
  void beforeEach() {
    System.out.println("Start one test method of CalcTest");
  }

  //Executed after each test method starts
  @AfterEach
  void afterEach() {
    System.out.println("Finish one test method of CalcTest");
  }

  //Test methods should not be private or static methods
  //The return value should be void because the value cannot be returned.
  @Test
  void testPlus() {
    System.out.println("Run testPlus: 2 + 3 = 5");
    Calc calc = new Calc(2);
    //1st argument:expected expected result
    //2nd argument:actual execution result
    //3rd argument:message Output message when failure
    assertEquals(5, calc.plus(3), "2 + 3 =Verification of 5");
  }

  @Test
  void testMinus() {
    System.out.println("Run testMinus: 5 - 2 = 3");
    Calc calc = new Calc(5);
    assertEquals(3, calc.minus(2), "5 - 2 =Verification of 3");
  }
}

reference:

Example of successful test

$ mvn test
[INFO] Scanning for projects...
[INFO] 
[INFO] ---------------------------< mygroup:myapp >----------------------------
[INFO] Building myapp 1.0.0
[INFO] --------------------------------[ jar ]---------------------------------
(Omission)
[INFO] --- maven-surefire-plugin:3.0.0-M5:test (default-test) @ myapp ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running myapp.CalcTest
Start CalcTest
Start one test method of CalcTest
Run testMinus: 5 - 2 = 3
Finish one test method of CalcTest
Start one test method of CalcTest
Run testPlus: 2 + 3 = 5
Finish one test method of CalcTest
CalcTest finished
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.087 s - in myapp.CalcTest
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

Example of test failure

$ mvn test
[INFO] Scanning for projects...
[INFO] 
[INFO] ---------------------------< mygroup:myapp >----------------------------
[INFO] Building myapp 1.0.0
[INFO] --------------------------------[ jar ]---------------------------------
(Omission)
[INFO] --- maven-surefire-plugin:3.0.0-M5:test (default-test) @ myapp ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running myapp.CalcTest
Start CalcTest
Start one test method of CalcTest
Run testMinus: 5 - 2 = 3
Finish one test method of CalcTest
Start one test method of CalcTest
Run testPlus: 2 + 3 = 5
Finish one test method of CalcTest
CalcTest finished
[ERROR] Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.063 s <<< FAILURE! - in myapp.CalcTest
[ERROR] myapp.CalcTest.testMinus  Time elapsed: 0.026 s  <<< FAILURE!
org.opentest4j.AssertionFailedError: 5 - 2 =Verification of 3==> expected: <3> but was: <7>
  at myapp.CalcTest.testMinus(CalcTest.java:53)

[INFO] 
[INFO] Results:
[INFO] 
[ERROR] Failures: 
[ERROR]   CalcTest.testMinus:53 5 - 2 =Verification of 3==> expected: <3> but was: <7>
[INFO] 
[ERROR] Tests run: 2, Failures: 1, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------

Sample to test collectively with assertAll

Sample code

package myapp;

import org.junit.jupiter.api.Test;

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

class CalcTest {

  @Test
  void testPlus() {
    Calc calc = new Calc(10);
    //Collectively verify
    //Even if you fail in the middle, verify everything without stopping
    assertAll(
     () -> assertEquals(30, calc.plus(20)),
     () -> assertEquals(99, calc.plus(90)),
     () -> assertEquals(11, calc.plus(50)),
     () -> assertEquals(40, calc.plus(30))
    );
  }
}

reference:

Example of test failure

$ mvn test
[INFO] Scanning for projects...
[INFO] 
[INFO] ---------------------------< mygroup:myapp >----------------------------
[INFO] Building myapp 1.0.0
[INFO] --------------------------------[ jar ]---------------------------------
(Omission)
[INFO] --- maven-surefire-plugin:3.0.0-M5:test (default-test) @ myapp ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running myapp.CalcTest
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.067 s <<< FAILURE! - in myapp.CalcTest
[ERROR] myapp.CalcTest.testPlus  Time elapsed: 0.044 s  <<< FAILURE!
org.opentest4j.MultipleFailuresError: 
Multiple Failures (2 failures)
  org.opentest4j.AssertionFailedError: expected: <99> but was: <100>
  org.opentest4j.AssertionFailedError: expected: <11> but was: <60>
  at myapp.CalcTest.testPlus(CalcTest.java:15)

[INFO] 
[INFO] Results:
[INFO] 
[ERROR] Failures: 
[ERROR]   CalcTest.testPlus:15 Multiple Failures (2 failures)
  org.opentest4j.AssertionFailedError: expected: <99> but was: <100>
  org.opentest4j.AssertionFailedError: expected: <11> but was: <60>
[INFO] 
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------

Exception throwing test sample

package myapp;

import org.junit.jupiter.api.Test;

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

class CalcTest {

  @Test
  void testPlus() {
    Calc calc = new Calc(100);
    //Assuming an ArithmeticException will occur if divided by 0
    ArithmeticException e =
      assertThrows(ArithmeticException.class,
        () -> calc.divide(0));
    assertTrue(e instanceof ArithmeticException);
  }
}

Reference material

Recommended Posts

Java automated test implementation with JUnit 5 + Apache Maven
Java automated test implementation with JUnit 5 + Gradle
[CircleCI 2.0] [Java] [Maven] [JUnit] Aggregate JUnit test results with CircleCI 2.0
[Java] Test private methods with JUnit
[Java] How to test for null with JUnit
Unit test with Junit.
[Java] JUnit4 test case example
Test Web API with junit
Try gRPC with Java, Maven
[Java] I want to test standard input & standard output with JUnit
Output JUnit test report in Maven
Test Spring framework controller with Junit
Control test order in Junit4 with enumeration
Java EE test (CDI / interceptor) with Arquillian
[Java] Handle Excel files with Apache POI
CICS-Run Java applications-(2) Build management with Maven
How to test private scope with JUnit
JUnit 5 gradle test fails with lombok annotation
Build Apache and Tomcat environment with Docker. By the way, Maven & Java cooperation
How to test interrupts during Thread.sleep with JUnit
Deploy Java web app to Azure with maven
Build and test Java + Gradle applications with Wercker
Easy JUnit test of Elasticsearch 2018 version with embedded-elasticsearch
Build an E2E test environment with Selenium (Java)
[Java] Hello World with Java 14 x Spring Boot 2.3 x JUnit 5 ~
Automate Java (Maven) project build with CircleCI + Orbs
Test code using mock with JUnit (EasyMock center)
Java Repository of Eclipse with Maven: Missing artifact ~
Mixin test cases with JUnit 5 and default methods
java, maven memo
Test the contents of an Excel file with JUnit
[JUnit 5 compatible] Write a test using JUnit 5 with Spring boot 2.2, 2.3
Search by POST request with Azure Search + Java Apache HttpClient
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
WebAPI unit test and integration test with SpringBoot + Junit5, 4 patterns
I wrote a test with Spring Boot + JUnit 5 now