javaspring-mvcmockmvc

Spring MVC: Print response only if returned status is not ok


I'm using this kind of code in my integration tests, which I find is quite typical when looking at other answers on this site:

mockMvc.perform(post("/xyz").contentType(...).content(...))
        .andDo(print())
        .andExpect(status().isOk)

My problem is the print() prints too many lines (the full request and response JSON strings) and clogs the output.

How can I make it print out the response (and only the response, not the request) and only if status is not ok?

I'm looking for something like this (which doesn't seem to exist):

mockMvc.perform(post("/xyz").contentType(...).content(...))
        .andExpect(status().isOk)
        .otherwiseDo(printResponse())

Solution

  • You could check the status in the ResultHandler

    mockMvc.perform(post("/xyz").contentType(...).content(...))
         .andDo(r -> { 
            if (r.getResponse().getStatus() != 200) {
                printResponse(r);
            }
        })
        .andExpect(status().isOk)