在我的项目中,我有 Maven 和 TestNG 工具。 我正在尝试将屏幕截图添加到 Allure 报告中。 如果我直接从测试中调用带有“@Attachment”注释的方法,则一切正常。
但是如果我在“@AfterMethod”部分调用它,屏幕截图就会添加到错误的报告中并且会混淆。
在这两种情况下,屏幕截图都会正确生成并保存在磁盘上。
我已经在这里看到了这个问题:Allure Framework: TestNG adapter incorrectly places @AfterMethod in report
我想,我的困难可能是因为 TestNG 适配器。
调用“@Attachment”方法的正确方法是什么? 我必须使用什么适配器才能避免此问题? 也许有人可以为我提供仅在测试失败时使用 ITestListener 制作屏幕截图的示例?
最佳答案
我在 Allure+TestNG 上遇到了类似的问题,并通过我的 BaseTest 类实现 IHookable 接口(interface)解决了这个问题。实现它的 run() 方法,你只需要告诉 TestNG 像往常一样运行测试,但捕获异常以在出现任何情况时截取屏幕截图
Javadoc 指出:
run() method will be invoked instead of each @Test method found. The invocation of the test method will then be performed upon invocation of the callBack() method of the IHookCallBack parameter.
代码片段如下:
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”
这将在捕获异常后立即截取屏幕截图,并将其放入 allure 报告的正确测试用例中
关于automated-tests - 倾城报道。使用 AfterMethod 将屏幕截图添加到错误报告中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29108159/