1

I am trying to test a controller with this method:

@RequestMapping(value="/test")
public ModelAndView generateRecords(@ModelAttribute("Employee") Employee employee) {

And I would like to know how can I create a unit testing for testing this. At the moment I am using:

MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/test");
//request.setMethod("GET");
new AnnotationMethodHandlerAdapter().handle(request, 
        new MockHttpServletResponse(), this.controller);

Running this test result in NULL value for ModelAttribute (Employee)

Is there any way to pass modelattribute object to Controller when doing integration testing??

Thanks


Just to summarize:

Solution to this problem is pick the html element names and fill the paramter values in MockHttpRequest object and pass it over.

Example:

MockHttpServletRequest httpServletRequest = MockRequestResponseGenerator.mockRequest(getServletInstance().getServletContext(), "POST", "/test", paramters);

//These paramters must be part of the ModelAttribute Object. Make sure, you are using custom property binding in case you have different object.

        httpServletRequest.setParameter("name", "SPRING MVC INTEGRATION TEST 
TEMP");
        httpServletRequest.setParameter("id", "1");
        httpServletRequest.setParameter("desc", "SPRING MVC INTEGRATION TEST DESC");


        getServletInstance().service(httpServletRequest, httpServletResponse);
Gumbo
  • 643,351
  • 109
  • 780
  • 844
Raj
  • 13
  • 1
  • 3

1 Answers1

1

You can set the values in the request as parameters following the OGNL paths matching the model attribute/form paths.

Teja Kantamneni
  • 17,402
  • 12
  • 56
  • 86
  • Good to hear... accept the answer if it helped solve your problem, so that other users will know... – Teja Kantamneni Aug 25 '11 at 15:41
  • how would you do if Employee had for instance a member "company" of type Company (which has, let's say, name and description fields)? how do you express the path to company.name and company.description? – fbiville Mar 04 '12 at 08:32