1

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)

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Why isn't there any built-in way to do it? Is this so uncommon? It feels weird to me, looks like I'm doing something wrong
0

MockMvc's content can only be a byte[]. So, you can have your code read body from a file like

public byte[] bytesFromPath(final String path) throws IOException {

    return Files.readAllBytes(Paths.get(path));
}
.content(bytesFromPath(new ClassPathResource("file-name").getPath()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.