首页 > 解决方案 > 创建屏幕截图 - Allure、JUnit5、Selenium

问题描述

有这方面的文件吗?JUnit4 有 @Rule 并且解决方案很简单。对于 JUnit5,我做了一个扩展public class TestWatcher implements AfterTestExecutionCallback,但我不知道在 @Override 方法中添加什么。

标签: seleniumscreenshotjunit5allure

解决方案


我已经设法解决了。截屏方法默认为一种:

@Attachment(value = "{testName} - screenshot", type = "image/png")
private byte[] makeScreenshotOnFailure(String testName) {

    return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
}

和 TestWatcher(扩展):

@Override
public void afterTestExecution(ExtensionContext extensionContext) throws Exception {

    Object test = extensionContext.getRequiredTestInstance();
    Field a = test.getClass().getDeclaredField("driver");
    a.setAccessible(true);
    driver = (WebDriver) a.get(test);

    Method method = extensionContext.getRequiredTestMethod();
    if (extensionContext.getExecutionException().isPresent()) {
        makeScreenshotOnFailure(method.getName());
    }
}

推荐阅读