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

RestAssured新手求助:如何以List格式发送PATCH请求体

解决RestAssured发送List格式PATCH请求体的问题

你的代码当前生成的是单个JSON对象,但接口要求的是包含单个对象的JSON数组(即List格式),同时还有2个细节需要调整,以下是修改方案:

关键修改点

  • 将单个订单对象放入List中,让RestAssured自动序列化为JSON数组
  • 添加contentType(ContentType.JSON),明确告诉服务器请求体是JSON格式
  • 正确处理names参数,确保生成数组而不是单个字符串

修改后的完整代码

@Test(dataProvider = "placeBulkOrders", timeOut = 120000)
public void placeBulkOrders(String userID, String names){
    try{
        int user = Integer.parseInt(userID);
        
        // 构建单个订单的Map对象
        Map<String, Object> orderMap = new HashMap<>();
        orderMap.put("meal", 1434751);
        // 分割names字符串为列表(如果dataProvider传入的是逗号分隔格式)
        List<String> nameList = Arrays.asList(names.trim().split(","));
        orderMap.put("names", nameList);
        orderMap.put("quantity", 2);
        orderMap.put("menu_item", 163606);
        orderMap.put("user", user);
        
        // 把订单对象放入List,构成数组格式的请求体
        List<Map<String, Object>> requestBody = new ArrayList<>();
        requestBody.add(orderMap);
        
        // 发送PATCH请求
        Response response = given().log().all()
                .baseUri(baseURI)
                .header("Accept", "application/json")
                .header("Authorization", "Token 055e7wfyr79r8790414f18dbe")
                .contentType(ContentType.JSON) // 必须设置,指定请求体格式
                .body(requestBody) // RestAssured自动序列化List为JSON数组
                .when().patch(patchOrder)
                .then().log().all()
                .extract().response();

        String responseBody = response.getBody().asString();

        // 断言逻辑保持不变,简化为assertTrue更规范
        Assert.assertTrue(responseBody.contains("1434751"));
        Assert.assertTrue(responseBody.contains(names));
        Assert.assertTrue(responseBody.contains("2"));
        Assert.assertTrue(responseBody.contains("163606"));
        Assert.assertTrue(responseBody.contains(Integer.toString(user)));

    }catch (Exception e){
        logger.error("Exception: ", e);
        Assert.fail("Exception thrown. Test Case Failed due to: " + e.getMessage(), e);
    }
}

补充说明

如果你的dataProvider传入的names已经是一个字符串数组(而非逗号分隔的单个字符串),可以直接替换nameList的生成代码为List<String> nameList = Arrays.asList(names);(注意这里的names需要是数组类型)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 10:07:34