I can perform actions on test failure by using:
@After
public void afterTest(Scenario scenario) {
if (scenario.isFailed()) {
/*Do stuff*/
}
}
However some of the actions I need to perform depend on the Exception that was thrown and in what context it was thrown. Is there a way to get the Throwable that caused the test to fail? For example in JUnit I would do this by extending TestWatcher and add a rule to my tests:
@Override
protected void failed(Throwable e, Description description) {
/*Do stuff with e*/
}
However the cucumber-junit iplementation does not allow the use of rules, so this solution would not work with Cucumber.
I don't think I need to explain why accessing a thrown exception on test failure would be useful, however I will still provide an Example:
My test environment is not always stable, so my tests might fail unexpectedly at any moment (there's no specific place I can try to catch the exception since it could occur at any time). When this happens I need the test to reschedule for another attempt, and log the incident so that we can get some good statistical data on the environment instability (when, how frequent, how long etc.)
If you just want to massage the result being sent to the report then you can extend the CucumberJSONFormatter and override the result method like this:
Then set the plugin option to:
I've implemented this method using reflections. You can't access directly to steps errors (stack trace). I've created this static method which allows you to access to "stepResults" attribute and then you can iterate and get the error and do whatever you want.
You can to this by writing your own custom implementation of
Formatter & Reporter
interface. The empty implementation ofFormatter
is theNullFormatter.java
which you can extend. You will need to provide implementations for theReporter
interface.The methods which would be of interest will be the
result()
of the Reporter interface and possibly thedone()
method of Formatter. The result() has theResult
object which has the exceptions.You can look at
RerunFormatter.java
for clarity.Github Formatter source
You will need to add this class(com.myimpl.CustomFormRep) to the plugin option.
More details on custom formatters.
You can use the rerun plugin to get a list of failed scenarios to run again. Not sure about scheduling a run of failed tests, code to create a batch job or schedule one on your CI tool.