Search code examples
springtestingmockmvcmodelattribute

Adding model attribute to spring MockMvc call


I'm writing a test for a simple controller.

The controller checks if the modelattribute "ADDED_OBJECT" exists and returns a success page and an error page when the modelattribute is missing. Testing the error path is no problem but I don't know how to trigger the success path, which is usually executed after a succesfull POST (Post/Redirect/Get) pattern. Is it possible to add the modelattribute to the mockMvc call?

Controller:

@GetMapping("/added")
public String addedContract(Model model) {
    if (!model.containsAttribute(ADDED_OBJECT)) {
        return ERROR_400;
    }
    return "added";
}

Test:

@Test
public void added() throws Exception {
    mockMvc.perform(get("/added"))
            .andExpect(status().isOk())
            .andExpect(content().string(not(containsString("400"))));
}

Thanks


Solution

  • The easiest way to do this is to set flashAttribute like this

     mockMvc.perform(get("/added").flashAttr("ADDED_OBJECT", "SomeObject"))
    

    This way you can control what gets passed to model object in controller and accordingly design your tests for various use cases.