Search code examples
unit-testingjunitcallbackannotationshandler

JUnit on failure callback/method


Is there any possibility to trigger a method whenever a testcase or assertion fails, in order to do some things when a testcase fails (e.g. Screenshot while UI-Testing, writing an error log, and so on...).

Maybe there is something like an annotation, I did not yet notice.

Thanks in advance!


Solution

  • You can use the TestWatcher rule and implement your own failed method to take a screenshot or whatever you need to do upon test failure. Slightly modified example from the official documentation:

    public static class WatchmanTest {
        private static String watchedLog;
    
        @Rule
        public TestRule watchman = new TestWatcher() {
            @Override
            protected void failed(Throwable e, Description description) {
                watchedLog += d + "\n";
                // take screenshot, etc.
            }
        };
    
        @Test
        public void fails() {
            fail();
        }
    }