测试具有@ModelAttribute作为参数的spring控制器方法

时间:2011-08-25 15:14:13

标签: spring model-view-controller integration integration-testing modelattribute

我正在尝试使用此方法测试控制器:

@RequestMapping(值= “/测试”)
public ModelAndView generateRecords(@ModelAttribute(“Employee”)Employee employee){

我想知道如何创建单元测试来测试它。目前我正在使用:

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

将此测试结果运行为ModelAttribute(Employee)的NULL值

在进行集成测试时,有没有办法将modelattribute对象传递给Controller?

由于


总结一下:

解决此问题的方法是选择html元素名称并填充MockHttpRequest对象中的参数值并将其传递。

示例:

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 个答案:

答案 0 :(得分:1)

您可以将请求中的值设置为符合模型属性/表单路径的OGNL路径之后的参数。