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

如何将JSONObject转为JSON格式解决RestAssured测试断言失败问题

解决RestAssured中JSONObject断言失败的问题

问题根源

你的断言失败是因为你在将JSONObject实例与响应体的字符串进行比较,两者属于不同类型,即使内容看起来完全一致,对象类型的不匹配也会导致断言失败。

可行解决方案

1. 使用JSONPath匹配单个字段(最推荐)

直接针对JSON中的具体字段进行断言,无需依赖整个JSON的字符串格式或键的顺序,是最健壮的方式:

@Test
void shouldGetHelloWorldMessage() {
    given()
      .standaloneSetup(controller)
    .when()
      .get("/hello-world-bean")
    .then()
      .statusCode(OK.value())
      .body("message", equalTo("Hello World Bean")); // 直接匹配message字段
}

2. 将JSONObject转换为字符串进行比较

利用json-simple库中JSONObject的toJSONString()方法,将预期对象转为字符串后与响应体字符串对比:

@Test
void shouldGetHelloWorldMessage() {
    JSONObject expected = new JSONObject();    
    expected.put("message","Hello World Bean");       
    
    given()
      .standaloneSetup(controller)
    .when()
      .get("/hello-world-bean")
    .then()
      .statusCode(OK.value())
      .body(is(equalTo(expected.toJSONString()))); // 转为字符串后比较
}

注意:这种方式要求响应体的JSON字符串格式(如空格、键的顺序)与JSONObject输出完全一致,否则仍会失败。

3. 使用Map替代JSONObject

RestAssured可以自动将响应JSON解析为Java Map,直接用Map作为预期值进行对比,无需担心格式问题:

import java.util.HashMap;
import java.util.Map;

@Test
void shouldGetHelloWorldMessage() {
    Map<String, Object> expected = new HashMap<>();
    expected.put("message", "Hello World Bean");       
    
    given()
      .standaloneSetup(controller)
    .when()
      .get("/hello-world-bean")
    .then()
      .statusCode(OK.value())
      .body(is(equalTo(expected))); // 用Map作为预期值
}

4. 提取响应体并解析后对比

先提取响应体字符串,将其转为JSONObject,再用JUnit的断言方法对比两个JSON对象:

import static org.junit.jupiter.api.Assertions.assertEquals;

@Test
void shouldGetHelloWorldMessage() {
    JSONObject expected = new JSONObject();    
    expected.put("message","Hello World Bean");       
    
    String responseBody = given()
      .standaloneSetup(controller)
    .when()
      .get("/hello-world-bean")
    .then()
      .statusCode(OK.value())
      .extract().asString(); // 提取响应体字符串
    
    JSONObject actual = new JSONObject(responseBody);
    assertEquals(expected, actual); // 对比两个JSONObject
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:25:12