Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 304
Patrick Adler Avatar asked Aug 15 '26 15:08

Patrick Adler


1 Answers

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.

like image 125
pvpkiran Avatar answered Aug 17 '26 12:08

pvpkiran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!