1

我是新手。使用 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"
        }
    ]
}

收到异常消息作为预期状态代码 <201> 但为 <500>。

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

任何人都可以让我知道我的代码有什么问题吗?

4

1 回答 1

0

As far as I understand, your created json is

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

but it requires

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

So you need to change the object of post body. My quick fix for this case is

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();
于 2021-07-04T03:43:08.870 回答