繁体   English   中英

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

[英]How execute code after each dynamic test?

有一个测试:

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);
                    }
                        }
                )));
    }
}

例如,为失败的测试创建一个屏幕。 导入org.junit.platform.launcher.TestExecutionListener的书面实现。

连接因此通常无法正常工作。 不执行完成。

基础:JUnit5-Maven-SpringBoot

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

如《 JUnit 5用户指南》中所述

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

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

根据您要在“侦听器”中尝试实现的目标,您也许可以在TestExecutionListener完成该任务,但是您不能在测试类中进行注册。 有关详细信息,请参见《用户指南》中的插入自己的测试执行监听器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM