Debugging Spring Mvc Tests
– written by Xavi | Java Jedi in the Marfeel Product Team
Sometimes, when implementing an integration test with Spring Mvc, you get an unexpected result. You can spend some time trying to figure out what is going on, but mockMvc comes with a method to help you with this.
For example, imagine you are testing a secured POST
. You provide the credentials using the user()
method:
mockMvc.perform(
post(ENTRY_POINT + "test.com/metrics")
.accept("application/json")
.contentType("application/json")
.content(serializeJSON(metrics))
.with(user(myUser).authorities(auth)))
.andExpect(status().isOk());
Instead of a 200 status code, you get a forbidden error:
java.lang.AssertionError: Status
Expected :200
Actual :403
But you are sure security is well set. So, what is going on?
One easy way to overcome this is to get more detail about what is happening. The way to do this is adding a print()
method:
mockMvc.perform(
post(ENTRY_POINT + "test.com/metrics")
.accept("application/json")
.contentType("application/json")
.content(serializeJSON(metrics))
.with(user(myUser).authorities(auth)))
.andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk());
This prints all the information regarding the request and response to the console. For instance, the part that interests us in this case is the response:
In this case, it clearly tells you that you are not sending the CSRF token with the request. Easy thing, since you can specify the token in the test request :)
mockMvc.perform(
post(ENTRY_POINT + "test.com/metrics")
.accept("application/json")
.contentType("application/json")
.content(serializeJSON(metrics))
.with(csrf())
.with(user(myUser).authorities(auth)))
.andExpect(status().isOk());