How to manage failed tests in JUnit5

孤街醉人 提交于 2021-02-07 09:54:38

问题


I'm migrating to JUnit5 and I'd like to know if there is an easy way in JUnit5 to know when a test failed or not, just like we had in JUnit4 with TestWatcher.

I did some research and found similar, but open questions, like this one: https://github.com/junit-team/junit5/issues/542 Since most of them are quite old, I'm asking just in case there is a recent solution.

The idea is to be able to do a screenshot or add some message into my log. So, is there a listener or extension or something that quickly allows me to manage the webdriver test's failure/pass/skip? Thanks in advance!


回答1:


OK, thanks glytching. It was harder than I expected, but finally made it. As you pointed me, we need to create an external class (e.g. WatcherExtension) implementing BeforeTestExecutionCallback and AfterTestExecutionCallback and then evaluate the exceptions using the context given by the extension. In this class we can add something like this:

@Override
public void afterTestExecution(ExtensionContext extensionContext) throws Exception {
    Method testMethod = extensionContext.getRequiredTestMethod();
    Boolean testFailed = extensionContext.getExecutionException().isPresent();
    if (testFailed) {
        if (!TESTDATA.excluded.contains(testMethod.getName())) {
            takeScreenshot(testMethod);
            logErrorMessage("Test " + testMethod.getName() + " failed on " + getAppVersion() + " using " + TESTDATA.browser);
        } else {
            logInfoMessage("Test " + testMethod.getName() + " was skipped on " + getAppVersion() + " using " + TESTDATA.browser);
        }
    } else {
        logInfoMessage(testMethod.getName() + " was successfully executed on " + getAppVersion() + " using " + TESTDATA.browser);
    }

Finally, you need to add this annotation to your test classes:

@ExtendWith(WatcherExtension.class)
public class MyTest extends TestFactory {
    @Test
    public void testMyTest() { //whatever  }
}

Personally, I think this is something really basic and should be directly implemented by JUnit5 in future versions. Thanks!



来源:https://stackoverflow.com/questions/51385936/how-to-manage-failed-tests-in-junit5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!