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:

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