我有一个使用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
文件夹下。
MockMvc
的content
只能是byte[]
。因此,您可以让代码从类似[]的文件中读取正文
public byte[] bytesFromPath(final String path) throws IOException { return Files.readAllBytes(Paths.get(path)); }
.content(bytesFromPath(new ClassPathResource("file-name").getPath()));