Is there a way in JUnit to detect within an @After annotated method if there was a test failure or error in the test case?
One ugly solution would b
I don't know any easy or elegant way to detect the failure of a Junit test in an @After method.
If it is possible to use a TestRule instead of an @After method, one possibility to do it is using two chained TestRules, using a TestWatcher as the inner rule.
Example:
package org.example;
import static org.junit.Assert.fail;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
public class ExampleTest {
private String name = "";
private boolean failed;
@Rule
public TestRule afterWithFailedInformation = RuleChain
.outerRule(new ExternalResource(){
@Override
protected void after() {
System.out.println("Test "+name+" "+(failed?"failed":"finished")+".");
}
})
.around(new TestWatcher(){
@Override
protected void finished(Description description) {
name = description.getDisplayName();
}
@Override
protected void failed(Throwable e, Description description) {
failed = true;
}
})
;
@Test
public void testSomething(){
fail();
}
@Test
public void testSomethingElse(){
}
}