java - 当我的测试失败且 chrome 浏览器关闭之前(@After)时,如何对 chrome 浏览器进行屏幕截图

标签 java maven selenium junit selenium-chromedriver

我已经运行了这段代码,并且在 Chrome 浏览器关闭后捕获了屏幕截图(@After) 如果我注释掉 CloseBrowser();屏幕截图被捕获,但 chrome 浏览器保持打开状态。 我希望在失败的测试中捕获屏幕截图,然后关闭浏览器。

总而言之 当前的屏幕截图是在浏览器关闭后捕获的,这只是一个空白的.png 我希望在浏览器关闭之前测试失败时捕获屏幕截图

谢谢

public class TestClass extends classHelper//has BrowserSetup(); and CloseBrowser(); {

 @Rule
 public ScreenshotTestRule my = new ScreenshotTestRule(); 

 @Before
 public void BeforeTest()
 {
      BrowserSetup();// launches chromedriver browser
 }

 @Test
 public void ViewAssetPage() 
 {
     //My test code here//And want to take screenshot on failure
 }

 @After
 public void AfterTest() throws InterruptedException
 {
      CloseBrowser();//closes the browser after test passes or fails
 }
}

class ScreenshotTestRule implements MethodRule {
    public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                try {
                    statement.evaluate();
                } catch (Throwable t) {
                    captureScreenshot(frameworkMethod.getName());
                    throw t; // rethrow to allow the failure to be reported to JUnit
                }
            }
            public void captureScreenshot(String fileName) {
                try {
                    new File("target/surefire-reports/").mkdirs(); // Insure directory is there
                    FileOutputStream out = new FileOutputStream("target/surefire-reports/screenshot-" + fileName + ".png");
                    out.write(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));
                    out.close();
                } catch (Exception e) {
                    // No need to crash the tests if the screenshot fails
                }
            }
        };
    }
}

最佳答案

您可以实现 TestNG 监听器以在测试之前或测试之后执行代码 或者当测试失败或成功时等。

像下面一样实现它,并将您的屏幕截图放在我展示的方法中

public class Listeners implements ITestListener {

Methods…
And put the screenshot code inside the method below:

@Override
    public void onTestFailure(ITestResult result) {
        code for screenshot
}

}

关于java - 当我的测试失败且 chrome 浏览器关闭之前(@After)时,如何对 chrome 浏览器进行屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59876744/

相关文章:

maven-2 - Maven 快速入门指南

maven - 为什么 Maven 会错误地将快照上传到发布存储库?

java - Jbehave 无法找到多个故事

java - 尝试从 blobstore 检索文件并使用谷歌应用引擎将其作为邮件附件发送

java - 如何在docker中运行maven selenium项目(Maven + Selenium + java + TestNg + docker)

java - 使用 PDFBox 在背景中创建渐变

Selenium IDE 向下箭头键

java - 使用 xpath 查找元素

java - 如何在猜谜游戏中使用 JOption?

java - 构造函数 Thread() 后面的代码如何工作?