【问题标题】:Create test hierarchy with @TestFactory使用 @TestFactory 创建测试层次结构
【发布时间】:2018-02-28 08:27:53
【问题描述】:

我正在使用 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】:

    当然。使用Collection&lt;DynamicNode&gt; 作为返回类型并创建任意数量的组。

    复制自: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 ✔
    

    【讨论】:

    • 这是完美的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 2015-07-15
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多