|
发表于 2024-4-18 12:38:23
|
显示全部楼层
要在JUnit 5与Allure报告中实现测试失败时截图并显示在报告中,可以使用以下步骤:
1. 首先,确保你的项目中已经添加了所需的依赖。
在`build.gradle`(Gradle)或`pom.xml`(Maven)文件中添加以下依赖:
- // Gradle
- dependencies {
- testCompile("io.qameta.allure:allure-junit5:2.13.7")
- ...
- }
复制代码
- <!-- Maven -->
- <dependency>
- <groupId>io.qameta.allure</groupId>
- <artifactId>allure-junit5</artifactId>
- <version>2.13.7</version>
- <scope>test</scope>
- </dependency>
复制代码
2. 创建一个实现了`TestWatcher`接口的自定义扩展类。
- import io.qameta.allure.Allure;
- import org.junit.jupiter.api.extension.BeforeEachCallback;
- import org.junit.jupiter.api.extension.ExtensionContext;
- import org.junit.jupiter.api.extension.TestWatcher;
- import java.io.ByteArrayInputStream;
- public class AllureTestWatcher implements TestWatcher, BeforeEachCallback {
- @Override
- public void beforeEach(ExtensionContext context) throws Exception {
- // 在每个测试方法开始前初始化一些操作(可选)
- }
- @Override
- public void testFailed(ExtensionContext context, Throwable cause) {
- // 在测试失败时进行截图并将截图添加到Allure报告中
- try {
- byte[] screenshot = takeScreenshot(); // 自定义截图方法
- Allure.addAttachment("Screenshot", new ByteArrayInputStream(screenshot));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private byte[] takeScreenshot() {
- // 实现截图的逻辑,这里只是示例
- // 你可以使用Selenium、Appium或其他截图工具进行实际的截图操作
- // 返回截图的字节数组
- return new byte[0];
- }
- }
复制代码
3. 在测试类上使用`@ExtendWith`注解,并将自定义扩展类引入。
- import org.junit.jupiter.api.Test;
- import org.junit.jupiter.api.extension.ExtendWith;
-
- @ExtendWith(AllureTestWatcher.class)
- public class MyTests {
-
- @Test
- public void testMethod1() {
- // 测试逻辑
- }
-
- @Test
- public void testMethod2() {
- // 测试逻辑
- }
-
- // ...
- }
复制代码
4. 运行测试,生成Allure报告。
在命令行中执行以下命令来运行测试并生成Allure报告:
- ./gradlew clean test
- allure serve build/allure-results
复制代码
或者使用其他构建工具(比如Maven),请根据你的项目配置进行相应的操作。
当测试方法失败时,会触发自定义扩展类中的`testFailed`方法,在其中会进行截图并将截图添加到Allure报告中。你可以通过Allure报告查看每个测试方法的截图和失败原因。请注意,由于截图的具体实现可能因测试框架或应用类型的不同而有所差异,需要根据实际情况进行适当调整。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|