【问题标题】:Unable to Post values via RestAssured无法通过 RestAssured 发布值
【发布时间】:2021-09-15 08:45:07
【问题描述】:

我是新手。使用 Restassured 开发代码 下面是我的代码

JSONObject request = new JSONObject(); // created an object
request.put("Name", "this is a");
request.put("ID", "012");
given().
header("Content-Type","application/json").
body(request.toJSONString()).
when().
post("http://localhost:3000/Shop").
then().
statusCode(201).
log().ifError();
My JSON File:
{
    "Shop":[
        {
            "ID":           "001",
            "Name": "ABC"
            
        },
        {
            "ID":           "002",
            "Name": "XYZ"
        }
    ]
}

我收到异常消息 预期状态代码 但为 。

at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)

谁能告诉我我的代码有什么问题?

【问题讨论】:

    标签: api post rest-assured


    【解决方案1】:

    据我了解,您创建的 json 是

    {
        "ID": "012",
        "Name": "this is a"
    }
    

    但它需要

    {
        "Shop":[
            {
                "ID":           "001",
                "Name": "ABC"
                
            },
            {
                "ID":           "002",
                "Name": "XYZ"
            }
        ]
    }
    

    所以你需要改变post body的对象。我对这种情况的快速解决方法是

    Map<String, Object> item = new HashMap<>();
    item.put("Name", "this is a");
    item.put("ID", "012");
    
    JSONObject shop = new JSONObject();
    shop.put("shop", Collections.singleton(item));
    
    given().log().all()
            .contentType(ContentType.JSON)
            .body(shop.toJSONString()).
            .when()
            .post("your-url")
            .then()
            .statusCode(201)
            .log().ifError();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多