java 在 Rest-assured 中使用 Json 文件作为有效负载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36579155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using a Json file in Rest-assured for payload
提问by Bhaskar Mishra
I have a huge JSON file to be POST as payload of a rest api call for testing purposes. I tried something like :
我有一个巨大的 JSON 文件作为用于测试目的的 rest api 调用的有效负载进行 POST。我试过类似的东西:
public void RestTest() throws Exception {
File file = new File("/Users/bmishra/Code_Center/stash/experiments/src/main/resources/Search.json");
String content = null;
given().body(file).with().contentType("application/json").then().expect().
statusCode(200).
body(equalTo("true")).when().post("http://devsearch");
}
and get error as :
并得到错误为:
java.lang.UnsupportedOperationException: Internal error: Can't encode /Users/bmishra/Code_Center/stash/experiments/src/main/resources/Search.json to JSON.
I can run by reading the file and passing the body as string and that works but I see i can directly pass the file object and this doesnt work.
我可以通过读取文件并将正文作为字符串传递来运行,并且可以运行,但是我看到我可以直接传递文件对象,但这不起作用。
After researching enough it seems that it doesnt work. I have opened up issue with rest-assured. https://github.com/jayway/rest-assured/issues/674
经过足够的研究,它似乎不起作用。我已经打开了放心的问题。 https://github.com/jayway/rest-assured/issues/674
采纳答案by Bhaskar Mishra
After posting the issue with rest-assured team. I have got a fix. I tested the fix and the issue is now resolved.
在与放心的团队发布问题后。我有一个修复。我测试了修复程序,问题现已解决。
Message from rest-assured:
安心寄语:
It should be fixed now so I've now deployed a new snapshot that should address this issue. Please try version 2.9.1-SNAPSHOT after having added the following Maven repository:
现在应该修复了,所以我现在部署了一个新的快照来解决这个问题。添加以下 Maven 存储库后,请尝试版本 2.9.1-SNAPSHOT:
<repositories>
<repository>
<id>sonatype</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
<snapshots />
</repository>
</repositories>
For more information : https://github.com/jayway/rest-assured/issues/674#issuecomment-210455811
欲了解更多信息:https: //github.com/jayway/rest-assured/issues/674#issuecomment-210455811
回答by Luke D. Smith
I use a generic method to read from the json and send that as a string, i.e:
我使用通用方法从 json 中读取并将其作为字符串发送,即:
public String generateStringFromResource(String path) throws IOException {
return new String(Files.readAllBytes(Paths.get(path)));
}
So in your example:
所以在你的例子中:
@Test
public void post() throws IOException {
String jsonBody = generateStringFromResource("/Users/bmishra/Code_Center/stash/experiments/src/main/resources/Search.json")
given().
contentType("application/json").
body(jsonBody).
when().
post("http://dev/search").
then().
statusCode(200).
body(containsString("true"));
}