I'm using MockMvc to test a method on my controller. But that controller method, as designed, expects a certain attribute to have been added to the model already, which would be the case in normal use. But when testing just this method, I can't figure out how to add the attribute to the model.
For example:
@RequestMapping(value = 'myEndpoint', method = RequestMethod.POST)
public String IWantToBeTested(Model model, @RequestParam(myParam) String paramValue) {
String needThis = model.asMap().get("NeedThisAttributeSetAlready");
String newThing = needThis + myParam;
model.AddAttribute("NewThing", newThing);
}
when I run the test with MockMvc, it supplies an empty model to this function, and I get an null pointer exception.
My test looks like this:
mockMvc.perform(post("/myEndpoint")
.param("myParam", "howdy")
.contentType("application/x-www-form-urlencoded"))
.andExpect(model().attributeExists("NewThing"))
.andExpect(model().attribute("NewThing", "oldThinghowdy"));
I've tried
@Mock
Model model;
but I don't know what to use for when().thenReturn(), because there aren't any get methods on the Model interface in Spring Boot, so I don't know what to mock. I tried:
when(model.asMap()).thenReturn(mockModel.asMap());
where mockModel is a static in my test class and has "NeedThisAttributeSetAlready" in it. That didn't work.
Any ideas?