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

RestAssured编写POST接口测试返回500错误,请求帮忙排查

问题排查与修复方案

你的代码主要存在两个核心问题,导致接口返回500错误:

  • 嵌套JSON结构错误:你通过request.put("bookingdates.checkin", "...")的方式设置字段,会生成平级的键值对,而接口要求bookingdates是一个包含checkin和checkout的嵌套JSON对象。
  • 数据类型不匹配:
    • totalprice字段接口要求是数字类型,你传递了字符串"677"
    • depositpaid字段接口要求是布尔类型,你传递了字符串"true"

以下是修正后的完整代码:

import static io.restassured.RestAssured.*;
import org.json.simple.JSONObject;
import org.testng.annotations.Test;
import io.restassured.http.ContentType;

public class Test01_CreateBooking {
    @Test
    public void CreateBooking() {
        // 外层请求对象
        JSONObject request = new JSONObject();
        // 创建bookingdates嵌套对象
        JSONObject bookingDates = new JSONObject();
        
        request.put("firstname", "Tom");
        request.put("lastname", "Payconiq");
        request.put("totalprice", 677); // 改为数字类型
        request.put("depositpaid", true); // 改为布尔类型
        bookingDates.put("checkin", "2023-06-06");
        bookingDates.put("checkout", "2023-07-07");
        request.put("bookingdates", bookingDates); // 将嵌套对象放入外层请求
        request.put("additionalneeds", "Breakfast");
        
        System.out.println(request.toJSONString());
        
        given()
            .contentType(ContentType.JSON)
            .accept(ContentType.JSON)
            .body(request.toJSONString())
        .when()
            .post("https://restful-booker.herokuapp.com/booking")
        .then()
            .statusCode(200)
            .log().all();
    }
}

关键修改说明:

  1. 单独创建bookingDates对象来存放checkin和checkout,再将这个对象作为bookingdates的值传入外层请求,符合接口要求的JSON结构。
  2. 修正totalprice和depositpaid的数据类型,匹配接口的参数要求。
  3. 移除了重复的header("Content-Type", "application/json"),因为contentType(ContentType.JSON)已经完成了这个头的设置,避免冗余。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:20:25