Take the 2-minute tour ×

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.


share|improve this question
In what kind of failure? When it can't click on a element? When it can't find an element immeaditely? When it can't find an element after waiting a little bit? When it can't launch the browser? The way I have done this is have a central method when the browser finds elements, wrap it in a try catch and in the catch, take a screenshot. Whenever I need to find an element, call this. Then this will handle it for you. –  Arran Sep 14 '12 at 23:13
With TestNG you can easly achive that. You only need a listner that takes the screenshot. If you are interested in a TestNG solution I will post my code for that tomorrow. –  Tarken Sep 18 '12 at 7:18
Possible dup of: Selenium 2 and JUnit4: How to capture screenshot on exception? –  Alberto Dec 13 '13 at 12:08
add comment

1 Answer

up vote 4 down vote accepted

A few quick searches led me to this:


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

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

Does that work for your problem?

share|improve this answer
Yes, that's awesome. I wish I'd seen this earlier. I've already gone with Tarken's approach. –  Ryan Shillington Nov 21 '12 at 22:16
add comment

Your Answer


