How to Apply JUnit 5

Creating a JUnit 5 build environment and applying JUnit 5 in Spring Boot

Build Environment

In a Gradle environment, you need a build file like the following build.gradle.

build.gradle

plugins {
    id 'java'
}

group 'com.devkuma'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}

test {
    useJUnitPlatform()
}
  • The dependency org.junit.jupiter:junit-jupiter-api is required.

When you create a project with an IDE, the directory structure looks like this.

.
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── devkuma
    │   │           └── Main.java
    │   └── resources
    └── test
        ├── java
        └── resources

Writing Test Code

/src/test/java/com/devkuma/junit5/JUnit5Test.java

package com.devkuma.junit5;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class JUnit5Test {
    @Test
    void success() {
        Assertions.assertEquals(3, 3);
    }

    @Test
    void fail() {
        Assertions.assertEquals(3, 5);
    }

    static class StaticTest {
        @Test
        void success() {
            Assertions.assertEquals(3, 3);
        }

        @Test
        void fail() {
            Assertions.assertEquals(3, 5);
        }
    }

    class InnerTest {
        @Test
        void success() {
            Assertions.assertEquals(3, 3);
        }

        @Test
        void fail() {
            Assertions.assertEquals(3, 5);
        }
    }
}

How to Apply It in Spring Boot

Since Spring Boot 2.2, JUnit 5 is provided by default. If you use JUnit 5, it is included in starter-test without separate configuration.

Spring Boot 2.2.x or later

testImplementation("org.springframework.boot:spring-boot-starter-test")
 
test {
    useJUnitPlatform()
}

Before Spring Boot 2.2.x

testImplementation("org.springframework.boot:spring-boot-starter-test") {
     exclude module : 'junit' 
}

testImplementation("org.junit.jupiter:junit-jupiter-api")
testCompile("org.junit.jupiter:junit-jupiter-params")
testRuntime("org.junit.jupiter:junit-jupiter-engine")

test {
     useJUnitPlatform() 
}