【问题标题】:How execute code after each dynamic test?每次动态测试后如何执行代码?
【发布时间】:2019-02-27 10:16:51
【问题描述】:

有一个测试:

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

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

【问题讨论】:

    标签: java spring-boot junit5 junit5-extension-model


    【解决方案1】:

    JUnit 5 User Guide中所述:

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

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

    根据您试图在“听众”中实现的目标,您可能能够在 TestExecutionListener 中实现这一目标,但您无法在测试类中注册它。详情请参阅用户指南中的Plugging in your own Test Execution Listener

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 2021-03-12
      相关资源
      最近更新 更多