我有一個使用 MockMvc 的 springBoot 2.1.9.RELEASE 應用程序。我想知道是否有辦法從文件中獲取正文內容mockMvc.perform(post("/hostel")
.content(withBodyFile("hostel.json"))就像我們可以做的那樣com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder (withBodyFile)
2 回答

繁華開滿天機
TA貢獻1816條經驗 獲得超4個贊
你可以使用類似的東西:
@SneakyThrows
private byte[] fromFile(String path) {
return new ClassPathResource(path).getInputStream().readAllBytes();
}
進而:
.content(fromFile("payload.json")))
請記住,該payload.json文件必須位于該src/test/resources文件夾下。

慕蓋茨4494581
TA貢獻1850條經驗 獲得超11個贊
MockMvc的content只能是一個byte[]。因此,您可以讓代碼從文件中讀取正文,例如
public byte[] bytesFromPath(final String path) throws IOException {
return Files.readAllBytes(Paths.get(path));
}
.content(bytesFromPath(new ClassPathResource("file-name").getPath()));
添加回答
舉報
0/150
提交
取消