Take a Screenshot if a Test Fails using JUnit

//Take a Screenshot if a Test Fails using JUnit

Take a Screenshot if a Test Fails using JUnit

How to check if a Test has failed using JUnit?

This blog introduces the JUnit TestWatcher Class. We can use this to detect the Status of a Test Case, and if it has failed, we can then invoke a Method to do something – in this case, report the error and take a screenshot.

There are other approaches to this, but the approach detailed here would be used instead of the usual JUnit @After annotation, and is useful as it will be invoked on any error.

The TestWatcher class Methods

Method Use
succeeded Invoked when a test succeeds
failed Invoked when a test fails
skipped Invoked when a test is skipped due to a failed assumption.
starting Invoked when a test is about to start
finished Invoked when a test method finishes (whether passing or failing)

more details about the TestWatcher Class can be found at: https://junit.org/junit4/javadoc/4.12/org/junit/rules/TestWatcher.html

Example Script

So here is an example with two test cases, using the @Before and @Test JUnit annotations, but instead of an @After block, we will use the TestWatcher finished Method instead.

This example uses Selenium WebDriver & JUnit

Obviously, in the real-world we could add this TestWatcher to a Base Class, and then inherit into our Test Classes, just like we would with the @Before and @After blocks, so we would only have to write this code once.

About Edgewords

Edgewords is a Training provider, specializing in Automated Testing Tools.

For Selenium WebDriver Java Training, please see our Selenium Training Pages

By |2018-12-18T10:21:42+00:00December 18th, 2018|Categories: Selenium WebDriver|Tags: , , , , |Comments Off on Take a Screenshot if a Test Fails using JUnit

About the Author:

Tom has been involved in automated software testing for over 20 years, both as a trainer and consultant. He is both an HP/Microfocus & Ranorex certified trainer.

Contact Info

Lasyard House, Underhill St. Bridgnorth WV16 4BB

Phone: +44 (0)333 939 8884