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

问题描述 投票:0回答:2

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

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

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

就像我们可以使用

com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder (withBodyFile)
java spring-boot spring-mvc mockmvc wiremock
2个回答
1
投票

您可以使用类似:

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

然后:

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

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


0
投票

MockMvccontent只能是byte[]。因此,您可以让代码从类似[]的文件中读取正文

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

    return Files.readAllBytes(Paths.get(path));
}
.content(bytesFromPath(new ClassPathResource("file-name").getPath()));
© www.soinside.com 2019 - 2024. All rights reserved.