简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM