You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Allure Reports:中间步骤失败时不终止测试的实现方法

解决方案:When步骤失败后继续执行Then步骤(Java 11 + Selenium + JUnit + Allure)

要实现测试步骤失败不中断后续执行,核心是用软断言替代JUnit默认的硬断言,同时结合Allure的步骤标记来单独记录每个步骤的状态。以下是具体实现方案:

1. 引入AssertJ软断言依赖

如果用Maven,在pom.xml中添加适配Java 11的AssertJ依赖:

<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.24.2</version>
    <scope>test</scope>
</dependency>

2. 测试类中实现软断言+Allure步骤标记

在测试类中初始化软断言实例,每个测试步骤用@Step标注,When步骤使用软断言验证(失败后不会抛出中断异常),继续执行Then步骤,最后统一汇总断言结果:

import io.qameta.allure.Step;
import org.assertj.core.api.SoftAssertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SampleTest {
    private WebDriver driver;
    private SoftAssertions softAssertions = new SoftAssertions();

    @Test
    public void testWithContinuationOnFailure() {
        driver = new ChromeDriver();
        givenInitialPage();
        whenPerformAction(); // 此步骤失败不会中断流程
        thenVerifyResults(); // 继续执行后续验证步骤
    }

    @Step("Given: 打开初始页面")
    private void givenInitialPage() {
        driver.get("https://example.com");
    }

    @Step("When: 执行核心操作步骤")
    private void whenPerformAction() {
        // 模拟可能失败的操作,用软断言验证
        String actualTitle = driver.getTitle();
        // 故意设置错误预期,模拟步骤失败场景
        softAssertions.assertThat(actualTitle).isEqualTo("Wrong Title");
    }

    @Step("Then: 验证最终结果")
    private void thenVerifyResults() {
        // 继续执行后续验证逻辑
        boolean isHeaderDisplayed = driver.findElement(By.tagName("h1")).isDisplayed();
        softAssertions.assertThat(isHeaderDisplayed).isTrue();
    }

    @AfterEach
    public void tearDown() {
        // 汇总所有断言结果,统一抛出失败信息
        softAssertions.assertAll();
        if (driver != null) {
            driver.quit();
        }
    }
}

3. Allure报告效果说明

每个@Step标注的步骤会在Allure报告中单独展示状态:When步骤失败会标记为红色,但Then步骤仍会执行并展示自身的状态(成功或失败),最终测试用例整体标记为失败,但所有步骤的执行记录都会完整保留。

额外优化点

如果需要在步骤失败时立即在Allure中记录详情,可以在软断言逻辑中手动添加附件:

try {
    softAssertions.assertThat(actualTitle).isEqualTo("Wrong Title");
} catch (AssertionError e) {
    Allure.addAttachment("When步骤失败详情", e.getMessage());
    // 不抛出异常,继续执行后续步骤
}

内容的提问来源于stack exchange,提问作者Vanessa2314

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 10:54:57