Java automated test implementation with JUnit 5 + Gradle

Overview

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

What is Junit 5

--JUnit is a Java automated testing framework

This environment

Basic sample of JUnit 5 + Gradle

Source code list

├── build.gradle
├── settings.gradle
└── src
    ├── main
    │   └── java
    │       └── myapp
    │           └── Calc.java
    └── test
        └── java
            └── myapp
                └── CalcTest.java

build.gradle

build.gradle


plugins {
  id 'java'
}

repositories {
  jcenter()
}

dependencies {
  // Junit Jupiter 5.5.Introduced 2
  //The following are introduced as dependencies
  // junit-jupiter-api:5.5.2
  // junit-jupiter-engine:5.5.2
  // junit-jupiter-platform-engine:1.5.2
  testImplementation 'org.junit.jupiter:junit-jupiter:5.5.2'
}

test {
  //Settings to use JUnit platform
  useJUnitPlatform()

  testLogging {
    //Display standard output and standard error output during testing
    showStandardStreams true
    //Output event(TestLogEvent)
    events 'started', 'skipped', 'passed', 'failed'
    //Output settings when an exception occurs(TestExceptionFormat)
    exceptionFormat 'full'
  }
}

reference:

settings.gradle

settings.gradle


rootProject.name = 'myapp'

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 only once before starting each test method
  @BeforeEach
  void beforeEach() {
    System.out.println("Start one test method of CalcTest");
  }

  //Executed only once 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

$ gradle test

> Task :test

myapp.CalcTest STANDARD_OUT
Start CalcTest

myapp.CalcTest > testMinus() STARTED

myapp.CalcTest > testMinus() STANDARD_OUT
Start one test method of CalcTest
Run testMinus: 5 - 2 = 3
Finish one test method of CalcTest

myapp.CalcTest > testMinus() PASSED

myapp.CalcTest > testPlus() STARTED

myapp.CalcTest > testPlus() STANDARD_OUT
Start one test method of CalcTest
Run testPlus: 2 + 3 = 5
Finish one test method of CalcTest

myapp.CalcTest > testPlus() PASSED

myapp.CalcTest STANDARD_OUT
CalcTest finished

BUILD SUCCESSFUL in 1s
3 actionable tasks: 3 executed

Example of test failure

$ gradle test

> Task :test FAILED

myapp.CalcTest STANDARD_OUT
Start CalcTest

myapp.CalcTest > testMinus() STARTED

myapp.CalcTest > testMinus() STANDARD_OUT
Start one test method of CalcTest
Run testMinus: 5 - 2 = 3
Finish one test method of CalcTest

myapp.CalcTest > testMinus() FAILED
    org.opentest4j.AssertionFailedError: 5 - 2 =Verification of 3==> expected: <3> but was: <7>
        at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
        at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
        at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:150)
        at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:542)
        at myapp.CalcTest.testMinus(CalcTest.java:48)

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 it fails 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

$ gradle test

> Task :test FAILED

myapp.CalcTest > testPlus() STARTED

myapp.CalcTest > testPlus() FAILED
    org.opentest4j.MultipleFailuresError: Multiple Failures (2 failures)
        org.opentest4j.AssertionFailedError: expected: <99> but was: <100>
        org.opentest4j.AssertionFailedError: expected: <11> but was: <60>
        at org.junit.jupiter.api.AssertAll.assertAll(AssertAll.java:80)
        at org.junit.jupiter.api.AssertAll.assertAll(AssertAll.java:44)
        at org.junit.jupiter.api.AssertAll.assertAll(AssertAll.java:38)
        at org.junit.jupiter.api.Assertions.assertAll(Assertions.java:2839)
        at myapp.CalcTest.testPlus(CalcTest.java:15)

1 test completed, 1 failed

FAILURE: Build failed with an exception.

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 + Gradle
Java automated test implementation with JUnit 5 + Apache Maven
[Java] Test private methods with JUnit
JUnit 5 gradle test fails with lombok annotation
Integration Test with Gradle
Unit test with Junit.
[Java] How to test for null with JUnit
[CircleCI 2.0] [Java] [Maven] [JUnit] Aggregate JUnit test results with CircleCI 2.0
Build and test Java + Gradle applications with Wercker
Java multi-project creation with Gradle
[Java] JUnit4 test case example
Test Web API with junit
Remote debugging with Gradle test
[Java] I want to test standard input & standard output with JUnit
Build a Java project with Gradle
Output test coverage with clover + gradle
Test Spring framework controller with Junit
[Java] Create an executable module with Gradle
How to filter JUnit Test in Gradle
Control test order in Junit4 with enumeration
CICS-Run Java applications-(3) Build management with Gradle
How to test private scope with JUnit
Primality test Java
Make SpringBoot1.5 + Gradle4.4 + Java8 + Docker environment compatible with Java11
Static code analysis with Checkstyle in Java + Gradle
How to test interrupts during Thread.sleep with JUnit
Easy JUnit test of Elasticsearch 2018 version with embedded-elasticsearch
Build an E2E test environment with Selenium (Java)
Using Gradle with VS Code, build Java → run
[Java] Hello World with Java 14 x Spring Boot 2.3 x JUnit 5 ~
Test code using mock with JUnit (EasyMock center)
Mixin test cases with JUnit 5 and default methods
Implementation of pagination function
Implementation of XLPagerTabStrip with TabBarController
Login function implementation with rails
[Rails 6] Pagination function implementation (kaminari)
[Rails] Make pagination compatible with Ajax
Create pagination function with Rails Kaminari
[Swift 5] Implementation of membership registration with Firebase
Java automated test implementation with JUnit 5 + Gradle
Compile with Java 6 and test with Java 11 while running Maven on Java 8
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
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
Check coverage with Codecov in Java + Gradle + Wercker configuration
I wrote a test with Spring Boot + JUnit 5 now
Install java with Homebrew
Use ProGuard with Gradle
Try JUnit test launch
Check Java toString () implementation
Change seats with java
Install Java with Ansible
Comfortable download with JAVA
Java JUnit brief note
First gradle build (Java)
Install Gradle with ubuntu16.04
Java Unit Test Library-Artery-Sample
Switch java with direnv
DataNucleus starting with Gradle
Heapsort implementation (in java)
[Rails] Test with RSpec
Test Nokogiri with Rspec.
Download Java with Ansible
Automatically test with Gauge
Load test with JMeter
Let's scrape with Java! !!
Use WebJars with Gradle
Build Java with Wercker