Search code examples
javaspring-bootspring-mvcmockmvcwiremock

mockMvc, get content from json file in SpringBoot


I have a springBoot 2.1.9.RELEASE application that uses MockMvc.

I would like to know if there is a way to get the content of the body from a file

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

like we can do with

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

Solution

  • You could use something like:

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

    And then:

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

    Just bear in mind that the payload.json file must be under the src/test/resources folder.