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



是否有办法获得类的名称,脚本是从@BeforeSuite注释中开始的,当不通过xml文件执行时?

这样做

:

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

返回类本身,其中包含@BeforeSuite注释和this:

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将自动注入它。这里应该有你要找的信息。

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

最新更新