0

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?

TimF
  • 151
  • 1
  • 2
  • 8
  • Could you share the piece of code that adds the `NeedThisAttributeSetAlready` attribute in the first place? Is it from a `@ModelAttribute` annotated method? My guess is it's not being triggered by your test configuration. – Brian Clozel Jun 09 '16 at 07:33
  • It's not a @ModelAttribute. It's sent from another server as a @RequestParam at an earlier step (this code is running inside an iframe) and I just add it to the model there. So something like: `@RequestMapping(value = 'firstEndpoint', method = RequestMethod.GET) public String IWantToBeTested(Model model, @RequestParam(saveThisThing) String saveMe) { ` – TimF Jun 09 '16 at 20:04

0 Answers0