2

On my project I have maven and TestNG tools. And I'm trying to add screenshots to Allure reports. If I call the method with "@Attachment" annotation directly from my tests, everything is okay.

But if I call it in "@AfterMethod" part, the screenshots are added to wrong reports and are mixed up.

In both cases screenshots are generated and saved on the disk correctly.

I've already seen the question here: Allure Framework: TestNG adapter incorrectly places @AfterMethod in report

And I guess, my difficulties might be because of TestNG adaptor.

What is the correct way of calling the "@Attachment" method? What adaptor do I have to use in order to avoid this problem? Maybe someone could provide me with example of using ITestListener to make screenshots only if a test is failed?

4

2 回答 2

5

我在 Allure+TestNG 上遇到过类似的问题,并通过我的 BaseTest 类实现IHookable接口来解决它。实现它的 run() 方法,你只需要告诉 TestNG 像往常一样运行测试,但捕获异常以在任何情况下截取屏幕截图

Javadoc 告诉我们:

将调用 run() 方法,而不是找到每个 @Test 方法。然后将在调用 IHookCallBack 参数的 callBack() 方法时执行测试方法的调用。

代码片段如下所示:

public class BaseTest implements IHookable {

    @Override
    public void run(IHookCallBack callBack, ITestResult testResult) {

        callBack.runTestMethod(testResult);
        if (testResult.getThrowable() != null) {
            try {
                takeScreenShot(testResult.getMethod().getMethodName());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Attachment(value = "Failure in method {0}", type = "image/png")
    private byte[] takeScreenShot(String methodName) throws IOException {
        return getWebDriver().getScreenshotAs(OutputType.BYTES);
    }
}

请注意,您还不能使用 testResult.isSuccess(),因为测试方法的结果执行是未知的,并且此时它处于“RUNNING”状态

这将在捕获异常后立即截取屏幕截图并将其放入正确的测试用例中

于 2015-05-29T12:44:57.850 回答
1

我在 Maven / TestNG 项目中也遇到了完全相同的问题,其中 @AfterMethod 未能成功附加屏幕截图。来自 Illia 的上述解决方案对我来说非常有效。谢谢伊利亚!

于 2016-07-21T11:54:52.217 回答