JUnit 5 User Guide

JUnit 5 User Guide
Stefan Bechtold
Sam Brannen
Johannes Link
Matthias Merdes
Marc Philipp
Christian Stein
Version 5.2.0
Table of Contents
1. Overview
1.1. What is JUnit 5?
1.2. Supported Java Versions
1.3. Getting Help
2. Installation
2.1. Dependency Metadata
2.2. Dependency Diagram
2.3. JUnit Jupiter Sample Projects
3. Writing Tests
3.1. Annotations
3.2. Test Classes and Methods
3.3. Display Names
3.4. Assertions
3.5. Assumptions
3.6. Disabling Tests
3.7. Conditional Test Execution
3.8. Tagging and Filtering
3.9. Test Instance Lifecycle
3.10. Nested Tests
3.11. Dependency Injection for Constructors and Methods
3.12. Test Interfaces and Default Methods
3.13. Repeated Tests
3.14. Parameterized Tests
3.15. Consuming Arguments
3.16. Test Templates
3.17. Dynamic Tests
4. Running Tests
4.1. IDE Support
4.2. Build Support
4.3. Console Launcher
4.4. Using JUnit 4 to run the JUnit Platform
4.5. Configuration Parameters
4.6. Tag Expressions
5. Extension Model
5.1. Overview
5.2. Registering Extensions
5.3. Conditional Test Execution
5.4. Test Instance Post-processing
5.5. Parameter Resolution
5.6. Test Lifecycle Callbacks
5.7. Exception Handling
5.8. Providing Invocation Contexts for Test Templates
5.9. Keeping State in Extensions
5.10. Supported Utilities in Extensions
5.11. Relative Execution Order of User Code and Extensions
6. Migrating from JUnit 4
6.1. Running JUnit 4 Tests on the JUnit Platform
6.2. Migration Tips
6.3. Limited JUnit 4 Rule Support
7. Advanced Topics
7.1. JUnit Platform Launcher API
8. API Evolution
8.1. API Version and Status
8.2. Experimental APIs
8.3. @API Tooling Support
9. Contributors
10. Release Notes
1. Overview
The goal of this document is to provide comprehensive reference documentation for programmers writing tests, extension authors, and engine authors as well as build tool and IDE vendors.

This document is also available as a PDF download.

Translations
This document is also available in Simplified Chinese.
1.1. What is JUnit 5?
Unlike previous versions of JUnit, JUnit 5 is composed of several different modules from three different sub-projects.

JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage

The JUnit Platform serves as a foundation for launching testing frameworks on the JVM. It also defines the TestEngine API for developing a testing framework that runs on the platform. Furthermore, the platform provides a Console Launcher to launch the platform from the command line and build plugins for Gradle and Maven as well as a JUnit 4 based Runner for running any TestEngine on the platform.

JUnit Jupiter is the combination of the new programming model and extension model for writing tests and extensions in JUnit 5. The Jupiter sub-project provides a TestEngine for running Jupiter based tests on the platform.

JUnit Vintage provides a TestEngine for running JUnit 3 and JUnit 4 based tests on the platform.

1.2. Supported Java Versions
JUnit 5 requires Java 8 (or higher) at runtime. However, you can still test code that has been compiled with previous versions of the JDK.

1.3. Getting Help
Ask JUnit 5 related questions on Stack Overflow or chat with us on Gitter.

2. Installation
Artifacts for final releases and milestones are deployed to Maven Central.

Snapshot artifacts are deployed to Sonatype’s snapshots repository under /org/junit.

2.1. Dependency Metadata
2.1.1. JUnit Platform
Group ID: org.junit.platform

Version: 1.2.0

Artifact IDs:

junit-platform-commons
Internal common library/utilities of JUnit. These utilities are intended solely for usage within the JUnit framework itself. Any usage by external parties is not supported. Use at your own risk!

junit-platform-console
Support for discovering and executing tests on the JUnit Platform from the console. See Console Launcher for details.

junit-platform-console-standalone
An executable JAR with all dependencies included is provided at Maven Central under the junit-platform-console-standalone directory. See Console Launcher for details.

junit-platform-engine
Public API for test engines. See Plugging in Your Own Test Engine for details.

junit-platform-gradle-plugin
Support for discovering and executing tests on the JUnit Platform using Gradle.

junit-platform-launcher
Public API for configuring and launching test plans — typically used by IDEs and build tools. See JUnit Platform Launcher API for details.

junit-platform-runner
Runner for executing tests and test suites on the JUnit Platform in a JUnit 4 environment. See Using JUnit 4 to run the JUnit Platform for details.

junit-platform-suite-api
Annotations for configuring test suites on the JUnit Platform. Supported by the JUnitPlatform runner and possibly by third-party TestEngine implementations.

junit-platform-surefire-provider
Support for discovering and executing tests on the JUnit Platform using Maven Surefire.
2.1.2. JUnit Jupiter
Group ID: org.junit.jupiter

Version: 5.2.0

Artifact IDs:

junit-jupiter-api
JUnit Jupiter API for writing tests and extensions.

junit-jupiter-engine
JUnit Jupiter test engine implementation, only required at runtime.

junit-jupiter-params
Support for parameterized tests in JUnit Jupiter.

junit-jupiter-migrationsupport
Migration support from JUnit 4 to JUnit Jupiter, only required for running selected JUnit 4 rules.
2.1.3. JUnit Vintage
Group ID: org.junit.vintage

Version: 5.2.0

Artifact ID:

junit-vintage-engine
JUnit Vintage test engine implementation that allows to run vintage JUnit tests, i.e. tests written in the JUnit 3 or JUnit 4 style, on the new JUnit Platform.
2.1.4. Bill of Materials (BOM)
The Bill of Materials POM provided under the following Maven coordinates can be used to ease dependency management when referencing multiple of the above artifacts using Maven or Gradle.

Group ID: org.junit

Artifact ID: junit-bom

Version: 5.2.0

2.1.5. Dependencies
All of the above artifacts have a dependency in their published Maven POMs on the following @API Guardian JAR.

Group ID: org.apiguardian

Artifact ID: apiguardian-api

Version: 1.0.0

In addition, most of the above artifacts have a direct or transitive dependency to the following OpenTest4J JAR.

Group ID: org.opentest4j

Artifact ID: opentest4j

Version: 1.1.0

2.2. Dependency Diagram
component diagram
2.3. JUnit Jupiter Sample Projects
The junit5-samples repository hosts a collection of sample projects based on JUnit Jupiter and JUnit Vintage. You’ll find the respective build.gradle and pom.xml in the projects below.

For Gradle, check out the junit5-jupiter-starter-gradle project.

For Maven, check out the junit5-jupiter-starter-maven project.

3. Writing Tests
A first test case
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

class FirstJUnit5Tests {

    @Test
    void myFirstTest() {
        assertEquals(2, 1 + 1);
    }

}
3.1. Annotations
JUnit Jupiter supports the following annotations for configuring tests and extending the framework.

All core annotations are located in the org.junit.jupiter.api package in the junit-jupiter-api module.

Annotation	Description
@Test
Denotes that a method is a test method. Unlike JUnit 4’s @Test annotation, this annotation does not declare any attributes, since test extensions in JUnit Jupiter operate based on their own dedicated annotations. Such methods are inherited unless they are overridden.
@ParameterizedTest
Denotes that a method is a parameterized test. Such methods are inherited unless they are overridden.
@RepeatedTest
Denotes that a method is a test template for a repeated test. Such methods are inherited unless they are overridden.
@TestFactory
Denotes that a method is a test factory for dynamic tests. Such methods are inherited unless they are overridden.
@TestInstance
Used to configure the test instance lifecycle for the annotated test class. Such annotations are inherited.
@TestTemplate
Denotes that a method is a template for test cases designed to be invoked multiple times depending on the number of invocation contexts returned by the registered providers. Such methods are inherited unless they are overridden.
@DisplayName
Declares a custom display name for the test class or test method. Such annotations are not inherited.
@BeforeEach
Denotes that the annotated method should be executed before each @Test, @RepeatedTest, @ParameterizedTest, or @TestFactory method in the current class; analogous to JUnit 4’s @Before. Such methods are inherited unless they are overridden.
@AfterEach
Denotes that the annotated method should be executed after each @Test, @RepeatedTest, @ParameterizedTest, or @TestFactory method in the current class; analogous to JUnit 4’s @After. Such methods are inherited unless they are overridden.
@BeforeAll
Denotes that the annotated method should be executed before all @Test, @RepeatedTest, @ParameterizedTest, and @TestFactory methods in the current class; analogous to JUnit 4’s @BeforeClass. Such methods are inherited (unless they are hidden or overridden) and must be static (unless the "per-class" test instance lifecycle is used).
@AfterAll
Denotes that the annotated method should be executed after all @Test, @RepeatedTest, @ParameterizedTest, and @TestFactory methods in the current class; analogous to JUnit 4’s @AfterClass. Such methods are inherited (unless they are hidden or overridden) and must be static (unless the "per-class" test instance lifecycle is used).
@Nested
Denotes that the annotated class is a nested, non-static test class. @BeforeAll and @AfterAll methods cannot be used directly in a @Nested test class unless the "per-class" test instance lifecycle is used. Such annotations are not inherited.
@Tag
Used to declare tags for filtering tests, either at the class or method level; analogous to test groups in TestNG or Categories in JUnit 4. Such annotations are inherited at the class level but not at the method level.
@Disabled
Used to disable a test class or test method; analogous to JUnit 4’s @Ignore. Such annotations are not inherited.
@ExtendWith
Used to register custom extensions. Such annotations are inherited.
Methods annotated with @Test, @TestTemplate, @RepeatedTest, @BeforeAll, @AfterAll, @BeforeEach, or @AfterEach annotations must not return a value.

Some annotations may currently be experimental. Consult the table in Experimental APIs for details.
3.1.1. Meta-Annotations and Composed Annotations
JUnit Jupiter annotations can be used as meta-annotations. That means that you can define your own composed annotation that will automatically inherit the semantics of its meta-annotations.

For example, instead of copying and pasting @Tag("fast") throughout your code base (see Tagging and Filtering), you can create a custom composed annotation named @Fast as follows. @Fast can then be used as a drop-in replacement for @Tag("fast").

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.junit.jupiter.api.Tag;

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Tag("fast")
public @interface Fast {
}
3.2. Test Classes and Methods
A test method is any instance method that is directly or meta-annotated with @Test, @RepeatedTest, @ParameterizedTest, @TestFactory, or @TestTemplate. A test class is any top level or static member class that contains at least one test method.

A standard test class
import static org.junit.jupiter.api.Assertions.fail;

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.Disabled;
import org.junit.jupiter.api.Test;

class StandardTests {

    @BeforeAll
    static void initAll() {
    }

    @BeforeEach
    void init() {
    }

    @Test
    void succeedingTest() {
    }

    @Test
    void failingTest() {
        fail("a failing test");
    }

    @Test
    @Disabled("for demonstration purposes")
    void skippedTest() {
        // not executed
    }

    @AfterEach
    void tearDown() {
    }

    @AfterAll
    static void tearDownAll() {
    }

}
Neither test classes nor test methods need to be public.
3.3. Display Names
Test classes and test methods can declare custom display names — with spaces, special characters, and even emojis — that will be displayed by test runners and test reporting.

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

@DisplayName("A special test case")
class DisplayNameDemo {

    @Test
    @DisplayName("Custom test name containing spaces")
    void testWithDisplayNameContainingSpaces() {
    }

    @Test
    @DisplayName("╯°□°)╯")
    void testWithDisplayNameContainingSpecialCharacters() {
    }

    @Test
    @DisplayName("
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值