使用 @TestFactory 创建测试层次结构

Create test hierarchy with @TestFactory

我正在使用 Junit 5 注释 @TestFactory 生成几个这样的测试:

@TestFactory
public Collection<DynamicTest> myTest() throws IOException {
    return fetchSomeTests().stream()
            .map(test -> {
                return dynamicTest(test.get("testDescription"), () -> doMyTest(test));
    }).collect(Collectors.toList());
}

是否可以分组组织生成的测试,就像使用 @Test 的不同 类 一样?

当然可以。使用 Collection<DynamicNode> 作为 return 类型并创建任意数量的组。

复制自:https://junit.org/junit5/docs/current/user-guide/#writing-tests-dynamic-tests

DynamicContainer 实例由显示名称和动态子节点列表组成,可以创建任意嵌套的动态节点层次结构。

这是生成嵌套动态容器和测试的示例:

@TestFactory
Stream<DynamicNode> dynamicTestsWithContainers() {
    return Stream.of("A", "B", "C")
        .map(input -> dynamicContainer("Container " + input, Stream.of(
            dynamicTest("not null", () -> assertNotNull(input)),
            dynamicContainer("properties", Stream.of(
                dynamicTest("length > 0", () -> assertTrue(input.length() > 0)),
                dynamicTest("not empty", () -> assertFalse(input.isEmpty()))
            ))
        )));
}

它会生成如下树:

│  ├─ DynamicTestsDemo ✔
│  │  ├─ dynamicTestsWithContainers() ✔
│  │  │  ├─ Container A ✔
│  │  │  │  ├─ not null ✔
│  │  │  │  └─ properties ✔
│  │  │  │     ├─ length > 0 ✔
│  │  │  │     └─ not empty ✔
│  │  │  ├─ Container B ✔
│  │  │  │  ├─ not null ✔
│  │  │  │  └─ properties ✔
│  │  │  │     ├─ length > 0 ✔
│  │  │  │     └─ not empty ✔
│  │  │  └─ Container C ✔
│  │  │     ├─ not null ✔
│  │  │     └─ properties ✔
│  │  │        ├─ length > 0 ✔
│  │  │        └─ not empty ✔