java - 获取@BeforeSuite注释中的类名 - TestNG - Java

标签 java selenium-webdriver testng

有没有办法在不通过 xml 文件执行时获取从 @BeforeSuite 注释内部启动脚本的类的名称?

这样做:

reportName = new Exception().getStackTrace()[0].getClassName();

返回包含 @BeforeSuite 注释的类本身:

reportName = new Exception().getStackTrace()[1].getClassName();

返回sun.reflect.NativeMethodAccessorlmpl

如果我直接从单独的类执行脚本,我想获取该信息,因为我使用它来命名我的范围报告文件名。

如果您想知道 @BeforeSuite 注释中的代码是什么样的:

// Set Extent Report file name from the global properties file
String reportName = ctx.getCurrentXmlTest().getSuite().getName();
if (reportName.equals("Default suite"))
{
    reportName = new Exception().getStackTrace()[0].getClassName();
}
String timeStamp = new SimpleDateFormat("HH.mm.ss").format(new Date());

// Initialize Extent Reports and modify the looks/output
String extentReportPath = "";
if (extent == null) {
    if (os.equals("Mac"))
    {
        extentReportPath = reportPath + "/" + project + "-" + reportName + "-" + environment + "-" + browser + "-" + timeStamp + ".html";
    }
    else if (os.equals("Windows"))
    {
        extentReportPath = reportPath + "\\" + project + "-" + reportName + "-" + environment + "-" + browser + "-" + timeStamp + ".html";
    }

    // Start new report
    extent = new ExtentReports(extentReportPath, true);
}

还有更多内容,但这是与我的问题相关的部分。

---更新---

这是我的解决方案:

// Set Extent Report file name from the global properties file
String reportName = ctx.getCurrentXmlTest().getSuite().getName();
if (reportName.equals("Default suite"))
{
    List<ITestNGMethod> allMethods = ctx.getSuite().getAllMethods();
    for (ITestNGMethod method : allMethods)
    {
        String fullMethod = method.toString();
        int indexOf = fullMethod.indexOf(".");
        reportName = fullMethod.replace(fullMethod.substring(indexOf), "");             }
}

最佳答案

您可以将参数 ITestContext 传递给 beforesuite 方法。 testNG 将自动注入(inject)它。这应该包含您要查找的信息。

context.getSuite().getAllMethods -> TestNGMethods.getRealClass() 或 getTestClass() 列表。

关于java - 获取@BeforeSuite注释中的类名 - TestNG - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39000812/

相关文章:

java - 尝试在 webDriver 中使用 @FindBy 时出现 java.lang.NullPointerException

java - 无论测试扩展如何,Jenkins 中的 Cobertura 代码覆盖率报告似乎都会提供相同的统计数据

java - 多个自定义 JComponents,只显示一个

java - 使用 Selenium 抓取网站时出现 StaleElementReferenceException

java - 如何在java中编写自定义函数/方法? (RFT)

python Selenium : How to check whether the WebDriver did quit()?

c# - 为什么 Selenium Firefox 驱动程序认为当父级溢出 :hidden? 时我的模态不显示

java - 父子项目maven

Java 外部类加载 ClassDefNotFoundError

java - 从 return 方法读取数组值