Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the attributes of a model contained in a ModelAndView object from the context of a controller test

I am new to Spring MVC and I'm in the process of learning how to test my controllers. I have a simple test:

@Test
public void shouldDoStuff()
{
    request.setRequestURI("/myCompany/123");
    ModelAndView mav = controller.getSomeDatas("123", request);
    assertEquals(mav.getViewName(), "company");
    assertTrue(mav.getModel().containsKey("companyInfo"));
    assertTrue(mav.getModel().containsKey("rightNow"));
    assertEquals(mav.getModel().get("companyInfo"), "123");
}

Here's my controller action:

@RequestMapping(value = "/myCompany/{companyGuid}", method = RequestMethod.GET)
public ModelAndView getSomeDatas(@PathVariable("companyGuid") String myGuid, HttpServletRequest request)
{
    /*ModelAndView mav = new ModelAndView("company");
    mav.addObject("companyInfo", myGuid);
    mav.addObject("rightNow", (new Date()).toString());
    return mav;*/
    Map<String, Object> myModel = new HashMap<String, Object>();

    myModel.put("companyInfo", myGuid);
    myModel.put("rightNow", (new Date()).toString());

    return new ModelAndView("company", "model", myModel);
}

I have a breakpoint set on the first assert. In the Display window in Eclipse, mav.getModel() returns exactly what I'd expect:

mav.getModel()
 (org.springframework.ui.ModelMap) {model={rightNow=Fri Nov 05 13:30:57 CDT 2010, companyInfo=123}}

However, any attempt to access the values in that model fails. For example, I assumed the following would work:

mav.getModel().get("companyInfo")
 null
mav.getModel().containsKey("companyInfo")
 (boolean) false

But as you can see, get("companyInfo") returns null, and containsKey("companyInfo") returns false.

When I swap out the commented section of the controller with the uncommented section, my tests work just fine, but then my jsp view breaks, because I'm trying to access properties of the model by saying things like ${model.companyInfo}, etc.

So I need to know at least one of two things (but better if you can answer both):

  1. If I leave the controller as shown, how can I access the attributes of the model in my test?
  2. If I swap out the commented section for the uncommented section, how can I access the attributes of the model in my jsp view?

Any help is appreciated.

like image 953
Samo Avatar asked Nov 29 '22 17:11

Samo


1 Answers

For question 1, Model provides a method that returns the model attributes as a map. In your test, you can do:

Map<String,Object> modelMap = mav.getModel().asMap();
modelMap.get("companyInfo");

Assuming you set companyInfo into the model, it should be there.

As for part2 of the question, I think someone else answered that already.

like image 171
sanimalp Avatar answered Mar 18 '23 13:03

sanimalp