【发布时间】:2016-08-29 15:06:32
【问题描述】:
我有 ApplicationTest 类和测试方法,我有测试和@BeforeMethod 和@AfterMethod,分别包含初始化和清理。
public class ApplicationTest extends BaseTest {
....
@BeforeMethod(alwaysRun = true)
public void openHomePage() {
......
headerPage.openMyApplicationsPage();
myAppPage.openAddNewAppPage();
newAppPage.createApp(appWithoutImages);
headerPage.openMyApplicationsPage();
myAppPage.openAddNewAppPage();
newAppPage.createApp(appWithImages);
}
@AfterMethod(alwaysRun = true)
public void cleanUp() {
headerPage.openMyApplicationsPage();
if (myAppPage.isApplicationPresent(appWithoutImages.getTitle())){
myAppPage.openApp(appWithoutImages.getTitle());
appPage.deleteApp();
}
headerPage.openMyApplicationsPage();
if (myAppPage.isApplicationPresent(appWithImages.getTitle())){
myAppPage.openApp(appWithImages.getTitle());
appPage.deleteApp();
}
driver.manage().deleteAllCookies();
}
@Test
public void correctInformationAboutApplicationTest() {
.....
}
@Test
public void testAppCreationWithoutImages() {
....
}
@Test
public void testAppEditing() {
}
}
它扩展了 BaseTest 类,我在其中编写了失败测试的截图逻辑:
public class BaseTest {
private static Settings settings = new Settings();
@BeforeSuite(alwaysRun = true)
public static void beforeSuite() {
driver = settings.getDriver();
BasePage.settings = settings;
driver.get(settings.getBaseUrl());
if (!settings.getBrowser().equals(BrowserType.HTMLUNIT))
driver.manage().window().maximize();
}
@AfterSuite(alwaysRun = true)
public static void afterClass() {
driver.close();
}
@AfterMethod
public void takeScreenshotWhenFailure(ITestResult result) {
String testDate = getCurrentDateAndTimeInSting();
if (ITestResult.FAILURE == result.getStatus()) {
captureScreenshot(result.getName() + " - " + testDate);
}
}
}
这里是这个方法的实现:
public static void captureScreenshot(String screenshotName) {
String pathToScreenshotDirectory = PATH_TO_SCREENSHOTS + " - " + TEST_DATE_FOR_PACKAGE;
try {
createDirectory(pathToScreenshotDirectory);
TakesScreenshot ts = (TakesScreenshot) driver;
File screenshot = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File(pathToScreenshotDirectory + "\\" + screenshotName + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
log.info("Screenshot taken: [ " + screenshotName + " ]");
}
它在没有@AfterMethod的其他测试类中工作正常,但是在ApplicationTest类中它在ApplicationTest类的@AfterMethod之后截屏,这是错误的截图,因为它不是@Test方法之后的截图。
在 ApplicationTest 类中的 @Test 方法之后,但在 ApplicationTest 类中的 @AfterMethod 之后,我如何才能为失败的测试截取正确的屏幕截图。
所以它必须在下一个顺序(如果我们从@Test开始计数):
- @Test
- @AfterMethod 属于
BaseTest类- @AfterMethod 属于
ApplicationTest类
【问题讨论】:
标签: java selenium testng screenshot