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

mockMvc, get content from json file in SpringBoot

我有一个使用 MockMvc 的 springBoot 2.1。9.RELEASE 应用程序。

我想知道是否有办法从文件中获取正文的内容

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

就像我们可以用

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

您可以使用类似的东西:

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

然后:

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

请记住 payload.json 文件必须在 src/test/resources 文件夹下。

MockMvccontent只能是一个byte[]。因此,您可以让代码从

这样的文件中读取正文
public byte[] bytesFromPath(final String path) throws IOException {

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