Blog logo on a black background with the words "Discover What's Next in Tech!"

JUnit TestWatcher

We show here how to write a JUnit extension that monitors test execution. Specifically, the execution of further tests in a test class should be prevented as soon as one of the test methods fails.

Background

Why do you need something like this?

We have an integration test that maps an entire workflow. The individual steps are each implemented as separate test methods.
They are executed in a fixed order using an order annotation. Of course, we could also pack all steps into a single test method, in which case it would also be aborted at the first error. The disadvantage here, however, would be that we could only see the progress via logging.
By mapping each step as an individual test method, we can see directly in the development environment which step we are in. However, it makes no sense to execute the other test methods of the integration test if a previous step fails. In this case, we therefore want to skip the execution of the other integration test steps.

The challenge

To realize this, we naturally do not want to include the same code in every test method over and over again: Per Assumption Query whether an error has already occurred, intercept errors, set a flag for the assumption.

Solution

We therefore simply create our own small extension. In this we implement the interface BeforeEachCallback. As a result, we have also developed the beforeEach available. In this we can offer a Assumption which skips the current test method if an error flag is set. Now we have to set the error flag. To do this, we also implement the TestWatcher-interface. We can use this to monitor the test execution. We are only really interested in the methods testAborted and testFailed. Here we simply set the flag anyFailed on true.

Using the extension is very simple. In every unit test class where this behavior is desired, we can now simply use the extension with

@ExtendsWith add:

 


JUnit 5 Assumptions

JUnit 5 TestWatcher Javadoc

Baeldung - Article about JUnit 5 TestWatcher API

Learn more about software development
Matthias Fischer

About ME

Matthias Fischer has a degree in general computer science and has been working as a software developer at doubleSlash since 2006. He has cross-industry experience in IT projects and works with well-known customers such as Deutsche Post Direkt GmbH, BMW AGFederal Printing Office, ZF AG and Zeppelin Systems together. Matthias has extensive expertise in Spring Boot, Java EE and Angular. His main focus is on back-end development, but for some time now he has also been involved in front-end development with Angular. Matthias is also passionate about software quality, automated testing and agile development.

All contributions from Matthias Fischer

Learn more

Further information on our website and in our newsletter

Arrow up