1

下面是我正在使用的代码

    JSONObject requestParams = new JSONObject();

    requestParams.put("something", "something value");
    requestParams.put("another.child", "child value");

这就是需要发布 API 的方式

{
   "something":"something value",
   "another": {
   "child": "child value"
   }
}

我收到一条错误消息,指出“需要另一个.child 字段”。

我该如何通过 restAssured 发布这个?其他不需要发布嵌套工作的 API,所以我假设这就是它失败的原因。

4

2 回答 2

2

您可以创建一个请求对象,然后让 RestAssured 库为您将对象序列化为 json。

例如:

        class Request {
            private String something;
            private Another another;

            public Request(final String something, final Another another) {
                this.something = something;
                this.another = another;
            }

            public String getSomething() {
                return something;
            }

            public Another getAnother() {
                return another;
            }
        }

       class Another {
            private String child;

            public Another(final String child) {
                this.child = child;
            }

            public String getChild() {
                return child;
            }
        }

..然后在测试方法中

@Test
public void itWorks() {
...
        Request request = new Request("something value", new Another("child value"));

        given().
                contentType("application/json").
                body(request).
        when().
                post("/message");
...
}

只是不要忘记这一行contentType("application/json"),以便库知道您要使用 json。

请参阅:https ://github.com/rest-assured/rest-assured/wiki/Usage#serialization

于 2018-02-23T23:43:56.387 回答
2

您发布的是因为JSONObject没有点分隔键路径的概念。

{
   "something":"something value",
   "another.child": "child value"
}

你需要再做一个JSONObject

JSONObject childJSON = new JSONObject():
childJSON.put("child", "child value");
requestParams.put("another", childJSON);
于 2018-02-23T23:51:22.477 回答