Search code examples
javaspringjunitspring-testspring-junit

How to use RunNotifier or RunListener using SpringJUnit4ClassRunner


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?


Solution

  • 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