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

问题描述 投票:0回答:1

我正在使用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一样?

testing junit junit5
1个回答
3
投票

当然。使用Collection<DynamicNode>作为返回类型,并根据需要创建任意数量的组。

复制自: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 ✔
© www.soinside.com 2019 - 2024. All rights reserved.