1

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

@RequestMapping(value="/test")
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 值中运行此测试结果

在进行集成测试时,有什么方法可以将模型属性对象传递给 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);
4

1 回答 1

1

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

于 2011-08-25T15:17:15.173 回答