简体   繁体   English

mockMvc,从 SpringBoot 中的 json 文件中获取内容

[英]mockMvc, get content from json file in SpringBoot

I have a springBoot 2.1.9.RELEASE application that uses MockMvc.我有一个使用 MockMvc 的 springBoot 2.1.9.RELEASE 应用程序。

I would like to know if there is a way to get the content of the body from a file我想知道是否有办法从文件中获取正文的内容

mockMvc.perform(post("/hostel")
    .content(withBodyFile("hostel.json"))

like we can do with就像我们可以做的那样

com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder (withBodyFile)

You could use something like:你可以使用类似的东西:

@SneakyThrows
private byte[] fromFile(String path) {
    return new ClassPathResource(path).getInputStream().readAllBytes();
}

And then:接着:

.content(fromFile("payload.json")))

Just bear in mind that the payload.json file must be under the src/test/resources folder.请记住, payload.json文件必须位于src/test/resources文件夹下。

MockMvc 's content can only be a byte[] . MockMvccontent只能是byte[] So, you can have your code read body from a file like因此,您可以让您的代码从文件中读取正文,例如

public byte[] bytesFromPath(final String path) throws IOException {

    return Files.readAllBytes(Paths.get(path));
}
.content(bytesFromPath(new ClassPathResource("file-name").getPath()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM