Allure TestNg:如何向报告Environment板块添加自定义环境信息
TestNG 框架下 Allure 报告 Environment 板块添加自定义环境信息的实现方法
Allure 的 Environment 板块默认读取测试结果目录(默认为allure-results)下的environment.properties或者environment.xml文件内容,结合 TestNG 监听器可以自动生成所需的环境信息,无需手动修改文件。
实现步骤
1. 编写 TestNG 套件监听器
实现ISuiteListener接口,在测试套件启动前自动采集系统信息并写入environment.properties文件,示例代码如下:
import org.testng.ISuite; import org.testng.ISuiteListener; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Properties; public class AllureEnvListener implements ISuiteListener { @Override public void onStart(ISuite suite) { Properties props = new Properties(); // 采集所需环境信息 props.setProperty("执行用户名", System.getProperty("user.name")); props.setProperty("操作系统", System.getProperty("os.name") + " " + System.getProperty("os.version")); props.setProperty("Java版本", System.getProperty("java.version")); try { props.setProperty("主机名", InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { props.setProperty("主机名", "未知"); } // 写入到allure-results目录 try (FileOutputStream fos = new FileOutputStream("allure-results/environment.properties")) { props.store(fos, "Allure 自定义环境信息"); } catch (IOException e) { e.printStackTrace(); } } }
2. 注册监听器
你可以任选以下一种方式注册编写好的监听器:
- 在
testng.xml中添加配置:
<suite name="测试套件"> <listeners> <listener class-name="你的包名.AllureEnvListener"/> </listeners> <!-- 其余测试类配置 --> </suite>
- 在测试类上添加
@Listeners注解:
@Listeners(AllureEnvListener.class) public class YourTest { // 测试方法 }
- 若使用Maven执行测试,可在
maven-surefire-plugin配置中添加监听器:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>你的插件版本</version> <configuration> <listeners> <listener> 你的包名.AllureEnvListener </listener> </listeners> </configuration> </plugin>
3. 验证效果
执行完测试后,运行allure serve allure-results命令生成并打开报告,即可在 Environment 板块看到添加的四项环境信息。
注意事项
如果运行监听器时提示找不到allure-results目录,可在写文件前先判断目录是否存在,不存在则主动创建即可。
内容的提问来源于stack exchange,提问作者ska
相关产品推荐
相关产品推荐

