jsoncat
jsoncat copied to clipboard
REST Assured 会自动将对象转换为 JSON 吗?
Guide 哥,有个序列化的疑问想问下。
问题
在测试代码 test/java/com/github/demo/user/UserControllerTest
中,最后一个测试方法 should_create_user_successful
中对 user
进行序列化。如果不进行序列化,也能测试通过。
分析
在一篇文章 Testing REST Endpoints Using REST Assured 看到如下:
REST Assured makes the conversion automatically to a JSON object.
测试
我尝试了如下更改,依然以通过测试:
@Test
void should_create_user_successful() {
UserDto user = new UserDto("压缩", "哈撒尅", 18);
with()//.body(jacksonSerializer.serialize(user)) // 我的修改
.body(user) // 我的修改
.header("Content-Type", "application/json")
.when().post("/user")
.then().
.statusCode(200);
}
我的结论
这么说来,这里是不是不需要序列化,直接传对象进去即可自动转化呢?
.body()
的实现如下:
// groovy
RequestSpecification body(Object object) {
notNull object, "object"
if (!isSerializableCandidate(object)) {
return body(object.toString());
}
this.requestBody = ObjectMapping.serialize(object, requestContentType, findEncoderCharsetOrReturnDefault(requestContentType), null, objectMappingConfig(), restAssuredConfig().getEncoderConfig());
this
}
* 第一次提问,感谢 Guide 哥辛苦开源!
底层ObjectMapping.groovy 默认还是jackson实现的序列化
那这个的意思是,可以不手动序列号化,让其自动序列化即可嘛? @hellohello-tom
#> 那这个的意思是,可以不手动序列号化,让其自动序列化即可嘛? @hellohello-tom
是的 老哥!感谢,我这里的序列化属于多余操作。我刚提交了一个commit修复了这个问题。再次感谢为jsoncat做出的贡献。