Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Selenium take a screenshot on test failure with JUnit?

When my test case fails, especially on our build server, I want to take a picture / screenshot of the screen to help me debug what happened later on. I know how to take a screenshot, but I was hoping for a way in JUnit to call my takeScreenshot() method if a test fails, before the browser is closed.

No, I don't want to go edit our bazillions of tests to add a try/catch. I could maybe, just possibly be talked into an annotation, I suppose. All of my tests have a common parent class, but I can't think of anything I can do there to solve this.

Ideas?

like image 559
Ryan Shillington Avatar asked Sep 14 '12 18:09

Ryan Shillington


People also ask

How do you take a screenshot on assert failure?

assertEquals(result, true) will take a screen shot in case the assertion fails because we enabled our listener. class to it.

Can Selenium take screenshots?

Selenium Webdriver allows you to take a screenshot using the getScreenShotAs method of the TakeScreenshot Interface. You can take a screenshot of a viewable area, full-page, or particular element.


2 Answers

A few quick searches led me to this:

http://blogs.steeplesoft.com/posts/2012/grabbing-screenshots-of-failed-selenium-tests.html

Basically, he recommends creating a JUnit4 Rule that wraps the test Statement in a try/catch block in which he calls:

imageFileOutputStream.write(     ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)); 

Does that work for your problem?

like image 120
Jeff Bowman Avatar answered Sep 22 '22 14:09

Jeff Bowman


If you want to quickly add this behavior to ALL your tests in the run you can use the RunListener interface to listen for test failures.

public class ScreenshotListener extends RunListener {

    private TakesScreenshot screenshotTaker;

    @Override
    public void testFailure(Failure failure) throws Exception {
        File file = screenshotTaker.getScreenshotAs(OutputType.File);
        // do something with your file
    }

}

Add the listener to your test runner like this...

JUnitCore junit = new JUnitCore();
junit.addListener(new ScreenshotListener((TakesScreenShots) webDriver));

// then run your test...

Result result = junit.run(Request.classes(FullTestSuite.class));
like image 45
dellsala Avatar answered Sep 23 '22 14:09

dellsala