首页 > 解决方案 > TestNG 中的 RunListener 等效项

问题描述

我正在将 Cucumber-JUnit 项目转换为 Cucumber-TestNg。在 Junit 中,我使用 RunListener 来抓取正在执行的 Gherkin 步骤。我使用此侦听器向我返回当前正在执行的步骤的场景,例如:在步骤“给定”条件或步骤“何时”或步骤“然后”等等。但是在 TestNg 中,我找不到一个类似的侦听器,它可以返回正在执行的 Gherkin 场景步骤。我尝试了其他 TestNg 监听器,但我无法解决这个问题。我发现 TestNg 侦听器处于与测试状态相关的状态,而不像 JuNit RunListener。建议即使有替代解决方案。

/**
 * Class used to do some report regarding the JUnit event notifier
 */
public class CustomJUnitListener extends RunListener {

  SeleniumTest test = null;

  public void setSeleniumTest(SeleniumTest test) {
    this.test = test;
  }

  /** {@inheritDoc} */
  @Override
  public void testFinished(Description description) throws Exception {
            // Get which scenario step under execution at run time..here    
  }

}```

//--------

让 TestRunner 使用这个类 @Runwith instaed of Cucumber.class


标签: javatestingcucumbertestnggherkin

解决方案


根据TestNG 文档。您可以使用一个IInvokedMethodListener或一个ITestListener可以帮助您实现目标的那些听众。

例如,使用 anIInvokedMethodListener你可以实现类似的东西:

public class TestNGCustomInvokedMethodListener implements IInvokedMethodListener {

  private static final Logger LOG = LoggerFactory.getLogger(TestNGCustomInvokedMethodListener.class);

  @Override
  public void beforeInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
   LOG.info("Running method: " + iInvokedMethod.getTestMethod().getMethodName());
  }

  @Override
  public void afterInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {

    LOG.info("Finished method: {} with result: {}", iInvokedMethod.getTestMethod().getMethodName(), statusToString(iTestResult.getStatus()));
  }

  private String statusToString(int status) {
    String statusStr;
    switch (status) {
      case ITestResult.FAILURE:
        statusStr = "FAILURE";
        break;

      case ITestResult.SKIP:
        statusStr = "SKIP";
        break;

      case ITestResult.STARTED:
        statusStr = "STARTED";
        break;

      case ITestResult.SUCCESS:
        statusStr = "SUCCESS";
        break;

     default:
        statusStr = "undefined";
        break;
    }

    return statusStr;
  }
}

最后你可以看看这篇文章,它很好地解释了如何使用配置 TestNG 监听器。


推荐阅读