Testing a spring controller method having @ModelAttribute as parameter

假如想象 提交于 2019-12-11 10:23:10

问题


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);

回答1:


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



来源:https://stackoverflow.com/questions/7192860/testing-a-spring-controller-method-having-modelattribute-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!