JUnit on failure callback/method

2019-06-17 05:29发布

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!

1条回答
Root(大扎)
2楼-- · 2019-06-17 06:15

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();
    }
}
查看更多
登录 后发表回答