问题描述
我正在尝试使用此方法测试控制器:
I am trying to test a controller with this method:
@RequestMapping(value ="/test")
公共ModelAndView generateRecords(@ModelAttribute("Employee")员工employee){
@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);
运行此测试结果时,ModelAttribute(Employee)的值为NULL
Running this test result in NULL value for ModelAttribute (Employee)
进行集成测试时,有什么方法可以将modelattribute对象传递给Controller?
Is there any way to pass modelattribute object to Controller when doing integration testing??
谢谢
总结一下:
解决此问题的方法是选择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);
推荐答案
您可以在与模型属性/表单路径匹配的OGNL
路径之后,将请求中的值设置为参数.
You can set the values in the request as parameters following the OGNL
paths matching the model attribute/form paths.
这篇关于测试以@ModelAttribute作为参数的弹簧控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!