3

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

Patrick Adler
  • 196
  • 2
  • 9
  • check my answer here. Eventhough the question is different, the solution is the same https://stackoverflow.com/questions/48156808/how-to-test-spring-rest-controller-with-mockito-when-if-controller-has-httpservl/48157132#48157132 – pvpkiran Jan 17 '18 at 15:42
  • I think I understand what you mean. But I cannot get it to work when trying like this: Model mockModel = mock(Model.class); when(mockModel.containsAttribute(ADDED_OBJECT)).thenReturn(true); – Patrick Adler Jan 17 '18 at 15:58
  • what error are you getting – pvpkiran Jan 17 '18 at 16:08
  • the model ist just empty – Patrick Adler Jan 17 '18 at 16:24

1 Answers1

13

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.

pvpkiran
  • 25,582
  • 8
  • 87
  • 134