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

San*_*Rey 1 java spring-mvc spring-boot mockmvc wiremock

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

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

mockMvc.perform(post("/hostel")
    .content(withBodyFile("hostel.json"))
Run Code Online (Sandbox Code Playgroud)

就像我们可以做的那样

com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder (withBodyFile)
Run Code Online (Sandbox Code Playgroud)

cas*_*lin 5

你可以使用类似的东西:

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

进而:

.content(fromFile("payload.json")))
Run Code Online (Sandbox Code Playgroud)

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