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(); } }
关键修改说明:
- 单独创建
bookingDates对象来存放checkin和checkout,再将这个对象作为bookingdates的值传入外层请求,符合接口要求的JSON结构。 - 修正
totalprice和depositpaid的数据类型,匹配接口的参数要求。 - 移除了重复的
header("Content-Type", "application/json"),因为contentType(ContentType.JSON)已经完成了这个头的设置,避免冗余。
内容的提问来源于stack exchange,提问作者Tester11
相关产品推荐
相关产品推荐

