Search code examples
javaseleniumjunitjunit4selenium-webdriver

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?


Solution

  • A few quick searches led me to a relevant article, "Grabbing Screenshots of Failed Selenium Tests" by Jason Lee, dated 24 Jan 2012. (Defunct original blogs.steeplesoft.com url: http://blogs.steeplesoft.com/posts/2012/grabbing-screenshots-of-failed-selenium-tests.html, now available from an archive.org mirror dated 7 Mar 2017.)

    In short, 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));
    

    In the comments, Leukipp links to a similar article "Performing an action when a test fails", by Thomas Sundberg, dated 8 Jul 2012, which offers a very similar @Rule but using getScreenshotAs(OutputType.FILE) which is then copied/moved to the intended destination.