gpt4 book ai didi

java - TestNG:如何将 IConfigurationListener2.beforeConfiguration ITestResult 链接到 ITestListener.onTestStart

转载 作者:行者123 更新时间:2023-12-01 08:58:50 25 4
gpt4 key购买 nike

我有 2 个 TestNG 监听器,它们将日志记录信息报告到日志文件以获取调试信息。它们是 IConfigurationListener2ITestListener。测试在多个线程中运行。

我的问题是,我需要将 IConfigurationListener2.onConfigurationFailure() 方法中的 ITestResult 链接到 ITestListener.onTestStart() ITestResult检索@Test ITestResult.getMethodName()。这可能吗?

TestListener 代码是:

public class TestListener implements ITestListener{
@Override
public void onTestStart(ITestResult result) {
System.out.println("Starting test method:" + result.getMethod().getMethodName());
}
}

IConfigurationListener2 是:

public class ConfigurationListener implements IConfigurationListener2 {
@Override
public void onConfigurationFailure(ITestResult result) {
System.out.println("Failed to run " + result.getMethod().getMethodName()
+ " for the test method:" + <code needed>);
}

TestNG 类是:

public class Script1 {

private int i =0;
@BeforeMethod
public void before(){
System.out.println("Starting before");
i++;
if (i==1){
throw new RuntimeException("forcing an exception");
}
}

@Test(testName="script1")
public void script1_run(){
System.out.println("Running script");
}

@Test(testName="script2")
public void script2_run(){
System.out.println("Running script");
}
}

那么我如何找出 @beforeMethod 失败的 @Test 方法。我想要这样的日志:

开始于
启动测试方法:script1_run
运行脚本
早于
开始之前测试方法script2_run运行失败

谢谢

最佳答案

您需要合并 2 个监听器:

public class MyNewListener implements IConfigurationListener2, ITestListener {

private final ThreadLocal<ITestResult> currentTest = new ThreadLocal<>();

@Override
public void onTestStart(ITestResult result) {
System.out.println("Starting test method:" + result.getMethod().getMethodName());
currentTest.set(result);
}

@Override
public void onConfigurationFailure(ITestResult result) {
System.out.println("Failed to run " + result.getMethod().getMethodName()
+ " for the test method:" + currentTest.get().getMethod().getMethodName());
}
}

ThreadLocal 用于跟踪并行运行。

免责声明:我没有在现实生活中测试听众。告诉我它是否有效。

编辑:配置方法失败后应该跳过测试

public class MyNewListener implements IConfigurationListener2, ITestListener {

private final ThreadLocal<ITestResult> failedConfiguration = new ThreadLocal<>();

@Override
public void onTestStart(ITestResult result) {
System.out.println("Starting test method:" + result.getMethod().getMethodName());
}

@Override
public void onConfigurationFailure(ITestResult result) {
failedConfiguration.set(result);
}

@Override
public void onTestSkipped(ITestResult result) {
System.out.println("Failed to run " + failedConfiguration.get().getMethod().getMethodName()
+ " for the test method:" + result.getMethod().getMethodName());
}
}

关于java - TestNG:如何将 IConfigurationListener2.beforeConfiguration ITestResult 链接到 ITestListener.onTestStart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41855983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com