I'm not a Java, Cucumber, Selenium athlete, but I've managed to cobble together some robust Cucumber tests that work. Each test tears down any data created to support it.

Problem is the environment the tests run in is less than robust and (as the tests rely on common data) when they fail the data can be left in an indeterminate state.

I don't really understand exception handlers, but want to write some code that will run when a test fails that checks the state of data and resets it so that a subsequent test will run and not fail due to a previous failure.

  • 1
    much better is of course to avoid mutating shared data when running a test as in a long run this will lead to all sorts of friction Commented Dec 19, 2017 at 7:40

2 Answers 2


You can achieve it using cucumber-jvm hooks. If a hook receives a Scenario as a parameter, you can know if it has failed or not.


public void afterFailedScenario(Scenario scenario) {
  if (scenario.isFailed()) {
     // Some code to execute...

Note the import of @After:

import cucumber.api.java.After;

The code under an @After is always run after each test, there is also an @Before that is run before each test, you also clean-up before each test.

Alternatively you could use a try/catch block in your test:

try {
  // Test steps that can fail and throw an exception
catch(Exception e){
  // This catch block catches all the exceptions
  // Clean your data

Ideally though, the tests should be independent, meaning they do not depend on the system being in a certain state or containing certain data, but rather setting up this state / data in the precondition (Given) of the test. Depending on the system state / common data will lead to flaky tests, which will make your test automation unreliable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.