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

基于REST Assured+Cucumber BDD,如何在Allure报告中记录堆栈跟踪、请求体与响应体?

在REST Assured + Cucumber BDD中为Allure报告添加堆栈跟踪、请求体和响应体

1. 配置核心依赖

先确保项目中包含以下依赖(以Maven为例):

<!-- Cucumber核心依赖 -->
<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>7.14.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-junit-platform-engine</artifactId>
    <version>7.14.0</version>
    <scope>test</scope>
</dependency>

<!-- REST Assured -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>

<!-- Allure集成依赖 -->
<dependency>
    <groupId>io.qameta.allure</groupId>
    <artifactId>allure-cucumber7-jvm</artifactId>
    <version>2.24.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.qameta.allure</groupId>
    <artifactId>allure-rest-assured</artifactId>
    <version>2.24.0</version>
    <scope>test</scope>
</dependency>

<!-- JUnit 5测试引擎 -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.10.0</version>
    <scope>test</scope>
</dependency>

2. 自动收集请求/响应数据

使用Allure官方提供的AllureRestAssured过滤器,它可以自动捕获请求和响应的完整数据并关联到报告:

import io.qameta.allure.restassured.AllureRestAssured;
import io.restassured.RestAssured;
import io.cucumber.java.Before;

public class TestHooks {

    @Before
    public void setupRestAssured() {
        // 为REST Assured添加Allure过滤器
        RestAssured.filters(new AllureRestAssured());
    }
}

如果需要自定义请求/响应的展示格式,也可以实现Filter接口手动控制:

import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import io.qameta.allure.Allure;
import java.io.ByteArrayInputStream;

public class CustomAllureFilter implements Filter {

    @Override
    public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
        Response response = ctx.next(requestSpec, responseSpec);

        // 添加请求体到Allure报告
        if (requestSpec.getBody() != null) {
            Allure.addAttachment("Request Body", "application/json", 
                new ByteArrayInputStream(requestSpec.getBody().toString().getBytes()), ".json");
        }

        // 添加响应体到Allure报告
        Allure.addAttachment("Response Body", "application/json", 
            new ByteArrayInputStream(response.getBody().asByteArray()), ".json");

        return response;
    }
}

然后在Hooks中替换为自定义过滤器即可。

3. 捕获堆栈跟踪并添加到报告

在Cucumber的@AfterStep钩子中捕获测试失败的异常,将堆栈跟踪作为附件添加到Allure报告:

import io.cucumber.java.AfterStep;
import io.cucumber.java.Scenario;
import io.qameta.allure.Allure;
import java.io.ByteArrayInputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

public class TestHooks {

    // ... 之前的setupRestAssured方法

    @AfterStep
    public void attachStackTraceOnFailure(Scenario scenario) {
        if (scenario.isFailed()) {
            Throwable throwable = scenario.getError();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            throwable.printStackTrace(pw);
            String stackTrace = sw.toString();

            // 添加堆栈跟踪附件
            Allure.addAttachment("Stack Trace", "text/plain", 
                new ByteArrayInputStream(stackTrace.getBytes()), ".txt");
        }
    }
}

4. 示例Step Definitions

以下是一个简单的API测试步骤实现:

import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Then;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class ApiTestSteps {

    private Response response;
    private final String BASE_URL = "https://jsonplaceholder.typicode.com";

    @Given("I prepare a valid post request body")
    public void preparePostRequestBody() {
        // 可在这里提前构造请求体,或通过参数传递
    }

    @When("I send POST request to {string} endpoint")
    public void sendPostRequest(String endpoint) {
        String requestBody = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
        
        response = given()
                .contentType("application/json")
                .body(requestBody)
                .when()
                .post(BASE_URL + endpoint);
    }

    @Then("response status code should be {int}")
    public void verifyStatusCode(int expectedCode) {
        assertEquals(expectedCode, response.getStatusCode());
    }
}

5. 示例Feature文件

Feature: Post API Testing
  Scenario: Create a new post entry
    Given I prepare a valid post request body
    When I send POST request to "/posts" endpoint
    Then response status code should be 201

生成并查看报告

测试执行完成后,运行以下命令生成并打开Allure报告:

allure serve target/allure-results

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 21:42:42