A Guide to JUnit 5 – JUnit 5指南

最后修改: 2016年 11月 19日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

JUnit is one of the most popular unit-testing frameworks in the Java ecosystem. The JUnit 5 version contains a number of exciting innovations, with the goal of supporting new features in Java 8 and above, as well as enabling many different styles of testing.

JUnit是Java生态系统中最受欢迎的单元测试框架之一。JUnit 5版本包含了许多令人兴奋的创新,目标是支持Java 8及以上版本的新功能,以及实现许多不同风格的测试。

2. Maven Dependencies

2.Maven的依赖性

Setting up JUnit 5.x.0 is pretty straightforward; we just need to add the following dependency to our pom.xml:

设置JUnit 5.x.0是非常简单的;我们只需要在我们的pom.xml中添加以下依赖性。

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

Furthermore, there’s now direct support to run Unit tests on the JUnit Platform in Eclipse, as well as IntelliJ. We can, of course, also run tests using the Maven Test goal.

此外,现在还直接支持在Eclipse以及IntelliJ的JUnit平台上运行单元测试。当然,我们也可以使用Maven测试目标来运行测试。

On the other hand, IntelliJ supports JUnit 5 by default. Therefore, running JUnit 5 on IntelliJ is pretty easy. We simply Right click –> Run, or Ctrl-Shift-F10.

另一方面,IntelliJ默认支持JUnit 5。因此,在IntelliJ上运行JUnit 5是相当容易的。我们只需右键单击 -> 运行,或按Ctrl-Shift-F10。

It’s important to note that this version requires Java 8 to work.

值得注意的是,这个版本需要Java 8才能工作

3. Architecture

3.建筑

JUnit 5 comprises several different modules from three different sub-projects.

JUnit 5包括来自三个不同子项目的几个不同模块。

3.1. JUnit Platform

3.1.JUnit平台

The platform is responsible for launching testing frameworks on the JVM. It defines a stable and powerful interface between JUnit and its clients, such as build tools.

该平台负责在JVM上启动测试框架。它在JUnit和它的客户(如构建工具)之间定义了一个稳定而强大的接口。

The platform easily integrates clients with JUnit to discover and execute tests.

该平台很容易将客户端与JUnit集成,以发现和执行测试。

It also defines the TestEngine API for developing a testing framework that runs on the JUnit platform. By implementing a custom TestEngine, we can plug 3rd party testing libraries directly into JUnit.

它还定义了TestEngine API,用于开发一个在JUnit平台上运行的测试框架。通过实现一个自定义的TestEngine,我们可以将第三方测试库直接插入JUnit中。

3.2. JUnit Jupiter

3.2.JUnit Jupiter

This module includes new programming and extension models for writing tests in JUnit 5. New annotations in comparison to JUnit 4 are:

本模块包括在JUnit 5中编写测试的新的编程和扩展模型。与JUnit 4相比,新的注释是。

  • @TestFactory – denotes a method that’s a test factory for dynamic tests
  • @DisplayName – defines a custom display name for a test class or a test method
  • @Nested – denotes that the annotated class is a nested, non-static test class
  • @Tag – declares tags for filtering tests
  • @ExtendWith – registers custom extensions
  • @BeforeEach – denotes that the annotated method will be executed before each test method (previously @Before)
  • @AfterEach – denotes that the annotated method will be executed after each test method (previously @After)
  • @BeforeAll – denotes that the annotated method will be executed before all test methods in the current class (previously @BeforeClass)
  • @AfterAll – denotes that the annotated method will be executed after all test methods in the current class (previously @AfterClass)
  • @Disable – disables a test class or method (previously @Ignore)

3.3. JUnit Vintage

3.3.JUnit复古

JUnit Vintage supports running tests based on JUnit 3 and JUnit 4 on the JUnit 5 platform.

JUnit Vintage支持在JUnit 5平台上运行基于JUnit 3和JUnit 4的测试。

4. Basic Annotations

4.基本注释

To discuss the new annotations, we divided this section into the following groups responsible for execution: before the tests, during the tests (optional), and after the tests:

为了讨论新的注释,我们将本节分为以下负责执行的小组:测试前、测试中(可选)和测试后。

4.1. @BeforeAll and @BeforeEach

4.1.@BeforeAll@BeforeEach

Below is an example of the simple code to be executed before the main test cases:

下面是一个在主要测试案例之前执行的简单代码的例子。

@BeforeAll
static void setup() {
    log.info("@BeforeAll - executes once before all test methods in this class");
}

@BeforeEach
void init() {
    log.info("@BeforeEach - executes before each test method in this class");
}

It’s important to note that the method with the @BeforeAll annotation needs to be static, otherwise the code won’t compile.

需要注意的是,带有@BeforeAll注解的方法需要是静态的,否则代码将无法编译。

4.2. @DisplayName and @Disabled

4.2.@DisplayName@Disabled

Now let’s move to new test-optional methods:

现在让我们转到新的测试选择方法。

@DisplayName("Single test successful")
@Test
void testSingleSuccessTest() {
    log.info("Success");
}

@Test
@Disabled("Not implemented yet")
void testShowSomething() {
}

As we can see, we can change the display name or disable the method with a comment, using new annotations.

正如我们所看到的,我们可以使用新的注释来改变显示名称或用注释来禁用该方法。

4.3. @AfterEach and @AfterAll

4.3.@AfterEach@AfterAll

Finally, let’s discuss the methods connected to operations after test execution:

最后,让我们讨论一下测试执行后与操作相关的方法。

@AfterEach
void tearDown() {
    log.info("@AfterEach - executed after each test method.");
}

@AfterAll
static void done() {
    log.info("@AfterAll - executed after all test methods.");
}

Please note that the method with @AfterAll also needs to be a static method.

请注意,带有@AfterAll的方法也需要是一个静态方法。

5. Assertions and Assumptions

5.断言和假设

JUnit 5 tries to take full advantage of the new features from Java 8, especially lambda expressions.

JUnit 5试图充分利用Java 8的新特性,特别是lambda表达式。

5.1. Assertions

5.1.断言

Assertions have been moved to org.junit.jupiter.api.Assertions, and have been significantly improved. As mentioned earlier, we can now use lambdas in assertions:

断言已被移至org.junit.jupiter.api.Assertions,并得到了显著的改进。如前所述,我们现在可以在断言中使用lambdas。

@Test
void lambdaExpressions() {
    List numbers = Arrays.asList(1, 2, 3);
    assertTrue(numbers.stream()
      .mapToInt(Integer::intValue)
      .sum() > 5, () -> "Sum should be greater than 5");
}

Although the example above is trivial, one advantage of using the lambda expression for the assertion message is that it’s lazily evaluated, which can save time and resources if the message construction is expensive.

虽然上面的例子是微不足道的,但对断言消息使用lambda表达式的一个好处是,它的评估是懒散的,如果消息的构造很昂贵,可以节省时间和资源。

It’s also now possible to group assertions with assertAll(), which will report any failed assertions within the group with a MultipleFailuresError:

现在也可以用assertAll()对断言进行分组,这将以MultipleFailuresError报告该组中任何失败的断言。

 @Test
 void groupAssertions() {
     int[] numbers = {0, 1, 2, 3, 4};
     assertAll("numbers",
         () -> assertEquals(numbers[0], 1),
         () -> assertEquals(numbers[3], 3),
         () -> assertEquals(numbers[4], 1)
     );
 }

This means it’s now safer to make more complex assertions, as we’ll be able to pinpoint the exact location of any failure.

这意味着现在做更复杂的断言是更安全的,因为我们将能够准确地指出任何故障的确切位置。

5.2. Assumptions

5.2.假设

Assumptions are used to run tests only if certain conditions are met. This is typically used for external conditions that are required for the test to run properly, but which aren’t directly related to whatever is being tested.

假设是用来运行测试的,只有当某些条件得到满足。这通常用于测试正常运行所需的外部条件,但这些条件与被测试的东西没有直接关系。

We can declare an assumption with assumeTrue(), assumeFalse(), and assumingThat():

我们可以用assumeTrue()assumeFalse()assumingThat()声明一个假设:

@Test
void trueAssumption() {
    assumeTrue(5 > 1);
    assertEquals(5 + 2, 7);
}

@Test
void falseAssumption() {
    assumeFalse(5 < 1);
    assertEquals(5 + 2, 7);
}

@Test
void assumptionThat() {
    String someString = "Just a string";
    assumingThat(
        someString.equals("Just a string"),
        () -> assertEquals(2 + 2, 4)
    );
}

If an assumption fails, a TestAbortedException is thrown and the test is simply skipped.

如果假设失败,就会抛出一个TestAbortedException,测试被简单地跳过。

Assumptions also understand lambda expressions.

假设也能理解lambda表达式。

6. Exception Testing

6.异常测试

There are two ways of exception testing in JUnit 5, both of which we can implement using the assertThrows() method:

在JUnit 5中,有两种异常测试的方式,我们都可以使用assertThrows()方法来实现。

@Test
void shouldThrowException() {
    Throwable exception = assertThrows(UnsupportedOperationException.class, () -> {
      throw new UnsupportedOperationException("Not supported");
    });
    assertEquals("Not supported", exception.getMessage());
}

@Test
void assertThrowsException() {
    String str = null;
    assertThrows(IllegalArgumentException.class, () -> {
      Integer.valueOf(str);
    });
}

The first example verifies the details of the thrown exception, and the second one validates the type of exception.

第一个例子验证了抛出异常的细节,第二个例子验证了异常的类型。

7. Test Suites

7.测试套件

To continue with the new features of JUnit 5, we’ll explore the concept of aggregating multiple test classes in a test suite, so that we can run those together. JUnit 5 provides two annotations, @SelectPackages and @SelectClasses, to create test suites.

为了继续JUnit 5的新功能,我们将探索在一个测试套件中聚合多个测试类的概念,以便我们可以一起运行这些测试。JUnit 5提供了两个注解,@SelectPackages@SelectClasses,来创建测试套件。

Keep in mind that at this early stage, most IDEs don’t support these features.

请记住,在这个早期阶段,大多数IDE并不支持这些功能。

Let’s have a look at the first one:

让我们来看看第一个问题。

@Suite
@SelectPackages("com.baeldung")
@ExcludePackages("com.baeldung.suites")
public class AllUnitTest {}

@SelectPackage is used to specify the names of packages to be selected when running a test suite. In our example, it will run all tests. The second annotation, @SelectClasses, is used to specify the classes to be selected when running a test suite:

@SelectPackage用于指定运行测试套件时要选择的包的名称。在我们的例子中,它将运行所有的测试。第二个注解,@SelectClasses,用于指定运行测试套件时要选择的类。

@Suite
@SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class})
public class AllUnitTest {}

For instance, the above class will create a suite that contains three test classes. Please note that the classes don’t have to be in one single package.

例如,上面的类将创建一个包含三个测试类的套件。请注意,这些类不一定要在一个单一的包中。

8. Dynamic Tests

8.动态测试

The last topic that we want to introduce is JUnit 5’s Dynamic Tests feature, which allows us to declare and run test cases generated at run-time. Contrary to Static Tests, which define a fixed number of test cases at the compile time, Dynamic Tests allow us to define the test cases dynamically in the runtime.

我们要介绍的最后一个主题是JUnit 5的动态测试功能,它允许我们声明和运行在运行时生成的测试用例。与静态测试相反,静态测试在编译时定义了固定数量的测试用例,动态测试允许我们在运行时动态地定义测试用例。

Dynamic tests can be generated by a factory method annotated with @TestFactory. Let’s have a look at the code:

动态测试可以由一个用@TestFactory.注解的工厂方法生成。让我们看看代码。

@TestFactory
Stream<DynamicTest> translateDynamicTestsFromStream() {
    return in.stream()
      .map(word ->
          DynamicTest.dynamicTest("Test translate " + word, () -> {
            int id = in.indexOf(word);
            assertEquals(out.get(id), translate(word));
          })
    );
}

This example is very straightforward and easy to understand. We want to translate words using two ArrayList, named in and out, respectively. The factory method must return a Stream, Collection, Iterable, or Iterator. In our case, we chose a Java 8 Stream.

这个例子非常简单明了,容易理解。我们想用两个ArrayList来翻译单词,分别名为inout。工厂方法必须返回一个StreamCollectionIterableIterator。在我们的案例中,我们选择了Java 8的Stream。

Please note that @TestFactory methods must not be private or static. The number of tests is dynamic, and it depends on the ArrayList size.

请注意,@TestFactory方法不能是私有或静态的。测试的数量是动态的,它取决于ArrayList的大小。

9. Conclusion

9.结论

In this article, we presented a quick overview of the changes that are coming with JUnit 5.

在这篇文章中,我们对JUnit 5所带来的变化做了一个快速概述。

We explored the big changes to the architecture of JUnit 5 in relation to the platform launcher, IDE, other Unit test frameworks, the integration with build tools, etc. In addition, JUnit 5 is more integrated with Java 8, especially with Lambdas and Stream concepts.

我们探讨了JUnit 5在平台启动器、IDE、其他单元测试框架、与构建工具的集成等方面的架构的巨大变化。此外,JUnit 5与Java 8的集成度更高,尤其是Lambdas和Stream概念。

The examples used in this article can be found in the GitHub project.

本文中使用的例子可以在GitHub项目中找到。