您可以创建一个请求对象,然后让 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