猿问

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

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

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

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

就像我们可以做的那样

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


江户川乱折腾
浏览 174回答 2
2回答

繁华开满天机

你可以使用类似的东西:@SneakyThrowsprivate byte[] fromFile(String path) {    return new ClassPathResource(path).getInputStream().readAllBytes();}进而:.content(fromFile("payload.json")))请记住,该payload.json文件必须位于该src/test/resources文件夹下。

慕盖茨4494581

MockMvc的content只能是一个byte[]。因此,您可以让代码从文件中读取正文,例如public byte[] bytesFromPath(final String path) throws IOException {    return Files.readAllBytes(Paths.get(path));}.content(bytesFromPath(new ClassPathResource("file-name").getPath()));
随时随地看视频慕课网APP

相关分类

Java
我要回答