【问题标题】:using a Json file in Rest-assured for payload在 Rest-assured 中使用 Json 文件作为有效负载
【发布时间】:2016-04-12 16:33:17
【问题描述】:

我有一个巨大的 JSON 文件要 POST 作为用于测试目的的 rest api 调用的有效负载。我试过类似的东西:

    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");


}

并得到错误:

java.lang.UnsupportedOperationException: Internal error: Can't encode /Users/bmishra/Code_Center/stash/experiments/src/main/resources/Search.json to JSON.

我可以通过读取文件并将正文作为字符串传递来运行,这可行,但我看到我可以直接传递文件对象,但这不起作用。

经过充分研究,似乎它不起作用。我已经打开了放心的问题。 https://github.com/jayway/rest-assured/issues/674

【问题讨论】:

  • 只是从文件中读取并将读取的内容发送给解析器。

标签: java json rest junit rest-assured


【解决方案1】:

在向放心的团队发布问题后。我有一个修复。我测试了修复程序,问题现已解决。

来自放心的消息:

现在应该修复了,所以我现在部署了一个新的快照来解决这个问题。请在添加以下 Maven 存储库后尝试版本 2.9.1-SNAPSHOT:

<repositories>
        <repository>
            <id>sonatype</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
            <snapshots />
        </repository>
</repositories>

欲了解更多信息:https://github.com/jayway/rest-assured/issues/674#issuecomment-210455811

【讨论】:

    【解决方案2】:

    我使用通用方法从 json 中读取并将其作为字符串发送,即:

    public String generateStringFromResource(String path) throws IOException {
    
        return new String(Files.readAllBytes(Paths.get(path)));
    
    }
    

    所以在你的例子中:

    @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"));
    }
    

    【讨论】:

    • 是的,我可以将文件内容作为字符串发送,但这是额外的一步。如果我阅读方法定义,它似乎提供了一种传递文件对象的方法。我想使用它,因为它使代码看起来更干净。
    • 这是代码中的一个额外步骤,但就性能而言,它实际上可能比使用 REST-assured 对文件进行编码更便宜。您所做的最新编辑应该可以根据我在 javadocs 中看到的内容进行,您的 json 内容格式是否正确?
    • :是的,最新的代码有效。我仍然想知道为什么放心的方法不将文件作为输入对象并抛出错误。我写了一个通用方法来确保每个测试我没有进行字符串转换并且工作正常。
    • 很高兴它的工作,你可能想通过他们的页面直接向 REST 有保证的人提出这个问题。
    猜你喜欢
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多