I want to get notified when a test fails. Ideally, I want to know if the test is passed or failed in my @After annotated method. I understand that their is a RunListener which can be used for this purpose but it works only if we run the test with JunitCore. Is there a way to get notified if a test case fails or something similar to RunListener which can be used with SpringJUnit4ClassRunner?
2 Answers
The Spring TestContext Framework provides a TestExecutionListener
SPI that can be used to achieve this.
Basically, if you implement TestExecutionListener
(or better yet extend AbstractTestExecutionListener
), you can implement the afterTestMethod(TestContext)
method. From the TestContext
that is passed in you can access the exception that was thrown (if there is one).
Here's the Javadoc for org.springframework.test.context.TestContext.getTestException()
:
Get the exception that was thrown during execution of the test method.
Note: this is a mutable property.
Returns: the exception that was thrown, or null if no exception was thrown
FYI: you can register your customer listener via the @TestExecutionListeners
annotation.
Regards,
Sam

- 29,611
- 5
- 104
- 136
-
Thanks a lot Sam. I am using testexecutionlistener now. – Arunav Feb 12 '14 at 18:17
An alternative is JUnits builtin TestWatcher
Rule.
The rule allows you to opt into what things you want to be notified for. Here is a compacted example from JUnit Github Docs
@Test
public class WatcherTest {
@Rule
public final TestRule watcher = new TestWatcher() {
@Override
protected void failed(Throwable e, Description) {}
// More overrides exists for starting, finished, succeeded etc
};
@Test
public void test() {}
}

- 7,151
- 11
- 51
- 83