Quantcast
Channel: Active questions tagged selenium - Stack Overflow
Viewing all articles
Browse latest Browse all 97762

How do i screenshot chrome browser when my tests fail and before the chrome browser closes (@After)

$
0
0

I have ran this code and the screenshot gets captured after the chrome browser closes (@After) If i comment out CloseBrowser(); the screenshot gets captured but the chromebrowser stay open. I want the screenshot to capture on a failed test then close the browser.

in summary The screenshot currently captures after the browser closes, which is just a blank .png I want the screenshot to capture when a test fails just before the browser closes

Thanks

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
                }
            }
        };
    }
}

Viewing all articles
Browse latest Browse all 97762

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>