You can use the JUnit TestRule TestWatcher . A TestRule
executes the code before and after the test method (similar to @Before
and @After
), but you have access to additional information and, more importantly, the test result. A TestWatcher defines methods such as succeeded()
, failed()
, starting()
and finished()
, which you can implement to receive event notifications.
The following example simply prints failed tests with failed statements.
public class TestWatcherTest { @Rule public TestWatcher testWatcher = new TestWatcher() { protected void failed(Throwable e, Description description) { System.out.println("" + description.getDisplayName() + " failed " + e.getMessage()); super.failed(e, description); } }; @Test public void test1() { Assert.assertEquals("hello world", 3, 4); } }
You obviously can do what you like, not System.out.println (). This produces as output:
test1(uk.co.farwell.junit.TestWatcherTest) failed hello world expected:<3> but was:<4>
Note that a failed statement is an exception, so you will have access to stacktrace, etc.
source share