我有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");
}
}


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

开始之前
启动测试方法:script1_run
运行脚本
开始之前
无法在以下测试方法之前运行:script2_run

谢谢,

最佳答案

您需要合并两个监听器:

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

09-06 10:41