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):
Any help is appreciated.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With