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!
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With