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

如何优化Java测试用例校验ReqRes接口返回Color字段的十六进制格式正确性

校验接口Color字段格式的优化方案

现有实现仅校验响应体整体包含#字符,存在大量误判场景:比如#出现在其他字段中、color字段长度不足/超长、颜色字符包含非十六进制字符等问题都无法识别,完全无法满足校验要求。

以下是两种可直接落地的实现方案:

方案1:直接在断言阶段完成校验(推荐)

利用RestAssured和Hamcrest的原生匹配器,代码最简洁,报错时会直接输出不匹配的字段值,方便定位问题:

import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.matchesPattern;

@Test
public void sixTest() {
    Specification.installSpec(Specification.requestSpec(), Specification.responseSpec());
    given()
            .when()
            .get("https://reqres.in/api/unknown")
            .then()
            .log().all()
            // 校验所有data数组下的color字段都符合十六进制颜色格式
            .body("data.color", everyItem(matchesPattern("^#[0-9A-Fa-f]{6}$")));
}

方案2:提取字段后逐个校验

如果需要对color字段做后续业务处理,可以选择这种更灵活的写法:

@Test
public void sixTest() {
    Specification.installSpec(Specification.requestSpec(), Specification.responseSpec());
    Response response = given()
            .when()
            .get("https://reqres.in/api/unknown")
            .then()
            .log().all()
            .extract().response();

    // 提取data数组中所有color字段的值
    List<String> colorList = response.jsonPath().getList("data.color");
    // 十六进制颜色格式正则
    String colorRegex = "^#[0-9A-Fa-f]{6}$";
    // 逐个校验格式
    for (String color : colorList) {
        Assert.assertTrue("非法颜色格式:" + color, color.matches(colorRegex));
    }
}

正则规则说明

用到的^#[0-9A-Fa-f]{6}$正则逻辑:

  • ^ 匹配字符串开头,避免前缀存在多余字符
  • # 匹配固定的#前缀
  • [0-9A-Fa-f]{6} 匹配6位合法的十六进制字符(支持大小写)
  • $ 匹配字符串结尾,避免后缀存在多余字符

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:15:03