Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 872
Benny Avatar asked Nov 13 '13 14:11

Benny


1 Answers

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();
    }
}
like image 178
kryger Avatar answered Sep 18 '22 15:09

kryger