java - 每次动态测试后如何执行代码?
问题描述
有一个测试:
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
每次动态测试后如何执行特定代码?
解决方案
如JUnit 5 用户指南中所述:
动态测试的执行生命周期与标准 @Test 用例的执行生命周期完全不同。具体来说,单个动态测试没有生命周期回调。这意味着@BeforeEach 和@AfterEach 方法及其对应的扩展回调是为@TestFactory 方法执行的,但不是为每个动态测试执行的。换句话说,如果您从 lambda 表达式中的测试实例访问字段以进行动态测试,则这些字段将不会被回调方法或由同一 @TestFactory 方法生成的各个动态测试的执行之间的扩展重置。
因此,您不能使用@AfterEach
方法或“之后”生命周期回调扩展之一(即,AfterEachCallback
或AfterTestExecutionCallback
)。
根据您在“听众”中尝试实现的目标,您可能能够在 a 中完成该目标TestExecutionListener
,但您无法在测试类中注册它。有关详细信息,请参阅用户指南中的插入您自己的测试执行侦听器。
推荐阅读
- python - 按日期时间合并元组的排序数组?
- php - Is it possible to have multiple file() tags in one php document
- python - 在 Python 中检查 Parquet 文件幻数
- android - android:设备的 GPU/CPU 在 RecyclerView 上过载
- asp.net - 当前上下文中不存在名称“X”
- r - 根据反应列定义一个新变量
- postgresql - PostgreSQL:无索引、临时表的大型插入的性能
- java - 尝试强制转换浮点变量时出现奇怪的 C# 行为(与 Java 相比)
- python-3.x - 从 winreg.QueryInfoKey 获取时间组件
- python - 使用python将一个csv文件的内容添加到另一个文件