在运行时使用唯一名称为每个步骤命名屏幕截图

Naming a screenshot for each step with a unique name at runtime

我正在使用 Java 开发 Selenium WebDriver 以实现自动化,TestNG 是我的框架。我是 运行 登录测试,我在其中记录范围报告中的每个步骤。我为每一步都有一个功能,对于每一步,我附上了一张截图。

我不确定如何使用唯一的描述性名称来命名每个屏幕截图。我尝试获取当前方法(步骤)名称,但似乎我需要创建一个匿名 class eveytime 和 everywhere 以根据以下代码获取当前 运行 方法名称。

String name = new Object(){}.getClass().getEnclosingMethod().getName();

这是我的代码。

@Test(priority = 0, testName="Verify Login")
public void login() throws Exception {
    lp = new LoginPage(driver, test);
    tm = new TabMenu(driver, test);
    driver.get(Constants.url);
    lp.verifyLoginPageLogo();
    lp.setUserName("admin");
    lp.setPassword("admin");
    lp.clickLoginBtn();
    tm.isCurrentTab("Dashboard");
}

public void verifyLoginPageLogo() throws IOException {
    String name = new Object(){}.getClass().getEnclosingMethod().getName();
    Assert.assertTrue(loginLogo.isDisplayed());
    test.log(LogStatus.PASS, "Logo is displayed", Screenshots.takeScreenshot(driver, name, test));      
}

public static String takeScreenshot(WebDriver driver, String name, ExtentTest test) throws IOException {

    String directory = "C:\Users\JACK\Documents\eclipse-workspace\OrangeHRM\Screenshots\";
    String fileName = name + ".png";
    File destFile = new File(directory + fileName);
    TakesScreenshot ss = (TakesScreenshot) driver;
    File sourceFile = ss.getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(sourceFile, destFile);
    String imgPath = test.addScreenCapture(directory+fileName);
    return imgPath;
}

还有其他方法吗?

当然,有很多选择:

  1. 如果您不关心文件名是什么,您可以使用 File.createTempFile()UUID.randomUUID() 来获取名称。这在语义上没有意义,但它可以很容易地为您提供唯一的文件名。
  2. 如果每个测试不需要多个文件名,您可以使用测试名称。在 JUnit 中,您可以使用 Test-Name Rule. For TestNG, there seem to be other solutions 使用 @Before 方法。即使您确实需要倍数,也可以将 test-name-rule 与序列号结合使用。
  3. 您可以只使用序列号,例如静态变量/单例中的整数。它不是很复杂,但它仍然可以工作。 ;)
  4. Java 获取当前方法名称并不是特别容易,因此您要么必须执行匿名对象,要么获取堆栈跟踪,无论哪种方式都有点痛苦而且不是特别性能。

以#2 为例,您可以修改您的代码,执行如下操作:

@Test(priority = 0, testName="Verify Login")
public void login(ITestContext context) throws Exception {
    lp = new LoginPage(driver, test);
    tm = new TabMenu(driver, test);
    driver.get(Constants.url);
    lp.verifyLoginPageLogo(context.getName(), 0);
    lp.setUserName("admin");
    lp.setPassword("admin");
    lp.clickLoginBtn();
    tm.isCurrentTab("Dashboard", context.getName(), 1);
}

public void verifyLoginPageLogo(String testName, int stepName) throws IOException {
    String name = new Object(){}.getClass().getEnclosingMethod().getName();
    Assert.assertTrue(loginLogo.isDisplayed());
    test.log(LogStatus.PASS, "Logo is displayed", Screenshots.takeScreenshot(driver, testName, stepName, test));      
}

public static String takeScreenshot(WebDriver driver, String testName, int stepName, ExtentTest test) throws IOException {
    String fileName = testName + "_" + stepName ".png";
    // the rest of your screenshot code
}

您甚至可以用另一个语义上有意义的词替换步骤编号,"loginLogo","dashboardTab" 如果这有帮助的话