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

IntelliJ IDEA中用RESTAssured校验数组字段annualBasePay并打印的方法

IntelliJ IDEA 下 RESTAssured 接口测试实现方案

前置依赖配置

首先在项目中引入RESTAssured相关依赖,以Maven为例,pom.xml添加如下配置:

<!-- RESTAssured核心依赖 -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>
<!-- Hamcrest匹配器依赖,用于字段值校验 -->
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

如果是Gradle项目,在build.gradle的dependencies块中添加:

testImplementation 'io.rest-assured:rest-assured:5.3.0'
testImplementation 'org.hamcrest:hamcrest-all:1.3'

功能实现代码

以下为完整测试代码示例,同时覆盖字段校验和控制台打印两个需求:

import io.restassured.RestAssured;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import org.junit.Test;

public class WorkerInfoInterfaceTest {

    @Test
    public void testAnnualBasePayField() {
        // 替换为实际的接口基础地址
        RestAssured.baseURI = "https://你的实际接口地址";

        // 发送请求、校验响应、提取字段
        String annualBasePayValue = given()
                // 按需补充请求头、请求参数、请求体等内容
                .header("Content-Type", "application/json")
                .when()
                .get("/你的接口路径")
                .then()
                // 先校验接口响应状态码正常
                .statusCode(200)
                // 校验annualBasePay字段存在(非空)
                .body("[0].jobRelatedInfoType.annualBasePay", notNullValue())
                // 校验字段值为124917
                .body("[0].jobRelatedInfoType.annualBasePay", equalTo("124917"))
                // 提取字段值
                .extract()
                .path("[0].jobRelatedInfoType.annualBasePay");

        // 打印字段值到控制台
        System.out.println("annualBasePay字段取值:" + annualBasePayValue);
    }
}

关键点说明

  • 响应根结构为数组,因此json路径以[0]开头表示取数组第一个元素,后续逐层嵌套取对应属性即可
  • 如果需要校验数组中所有元素的annualBasePay字段,可将路径调整为*.jobRelatedInfoType.annualBasePay,结合遍历逻辑实现全量校验
  • 代码示例基于JUnit测试框架编写,若使用TestNG仅需替换@Test注解的导入包即可

内容的提问来源于stack exchange,提问作者Bhavya Sri Chundru

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:54:03