我正在使用 Java 开发 Selenium WebDriver 以实现自动化,TestNG 是我的框架。我正在运行登录测试,其中我在范围报告中记录每个步骤。我为每个步骤都有一个函数,并且对于每个步骤,我都附上了屏幕截图。
我不确定如何使用唯一的描述性名称来命名每个屏幕截图。我尝试获取当前方法(步骤)名称,但似乎我需要创建一个匿名类 eveytime 和 eveywhere 来获取当前正在运行的方法名称,如下代码所示。
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;
}
还有其他方法可以做到这一点吗?
最佳答案
当然,有很多选择:
- 如果您不关心文件名是什么,可以使用
File.createTempFile()
或仅使用UUID.randomUUID()
来获取名称。这在语义上没有意义,但它可以轻松地为您提供唯一的文件名。 - 如果每个测试不需要多个文件名,则可以使用测试名称。在 JUnit 中,您可以使用 Test-Name Rule 。对于TestNG,似乎有other solutions使用
@Before
方法。即使您确实需要多个,您也可以将 test-name-rule 与序列号组合起来。 - 您可以只使用序列号,例如静态变量/单例中的整数。它不是很复杂,但仍然可以工作。 ;)
- 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”
关于java - 在运行时使用唯一的名称为每个步骤命名屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50255636/