首页 > 解决方案 > 每次动态测试后如何执行代码?

问题描述

有一个测试:

package com.cdek.qa_auto.config;
import com.cdek.qa_auto.utils.CdekJUnitListener;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;


/***
 *
 */
@SpringBootTest
public class JUnit5Test {
    public JUnit5Test() throws Exception {}

    @BeforeEach
    public void beforeEach() throws Exception {
        Launcher launcher = LauncherFactory.create();
        TestExecutionListener listener = new CdekJUnitListener();
        launcher.registerTestExecutionListeners(listener);
    }

    @TestFactory
    public Stream<DynamicTest> test() throws Exception {
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("12");
        list.add("123");
        list.add("1234");
        list.add("12345");

        return list.stream().map(item -> (
                dynamicTest("test_" + item, () -> {
                    if ("1".equalsIgnoreCase(item)) {
                        System.out.println("fail");
                        fail("fail");
                    } else if ("12".equalsIgnoreCase(item)) {
                        assertTrue(false);
                    } else if ("123".equalsIgnoreCase(item)) {
                        throw new Exception("msg");
                    } else {
                        assertTrue(true);
                    }
                        }
                )));
    }
}

例如,为跌倒的测试制作一个屏幕。import org.junit.platform.launcher.TestExecutionListener 的书面实现。

连接所以通常没有工作。不进入执行Finished。

依据:JUnit5-Maven-SpringBoot

每次动态测试后如何执行特定代码?

标签: javaspring-bootjunit5junit5-extension-model

解决方案


JUnit 5 用户指南中所述:

动态测试的执行生命周期与标准 @Test 用例的执行生命周期完全不同。具体来说,单个动态测试没有生命周期回调。这意味着@BeforeEach 和@AfterEach 方法及其对应的扩展回调是为@TestFactory 方法执行的,但不是为每个动态测试执行的。换句话说,如果您从 lambda 表达式中的测试实例访问字段以进行动态测试,则这些字段将不会被回调方法或由同一 @TestFactory 方法生成的各个动态测试的执行之间的扩展重置。

因此,您不能使用@AfterEach方法或“之后”生命周期回调扩展之一(即,AfterEachCallbackAfterTestExecutionCallback)。

根据您在“听众”中尝试实现的目标,您可能能够在 a 中完成该目标TestExecutionListener,但您无法在测试类中注册它。有关详细信息,请参阅用户指南中的插入您自己的测试执行侦听器。


推荐阅读