测试以@ModelAttribute为参数的spring控制器方法

测试以@ModelAttribute为参数的spring控制器方法,spring,model-view-controller,integration,integration-testing,modelattribute,Spring,Model View Controller,Integration,Integration Testing,Modelattribute,我正在尝试使用以下方法测试控制器: @请求映射(value=“/test”) 公共模型和视图生成器记录(@modeldattribute(“Employee”)Employee){ 我想知道如何创建一个单元测试来测试它。目前我正在使用: MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/test"); //request.setMethod("GET"); new Anno

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

@请求映射(value=“/test”)
公共模型和视图生成器记录(@modeldattribute(“Employee”)Employee){

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

MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/test");
//request.setMethod("GET");
new AnnotationMethodHandlerAdapter().handle(request, 
        new MockHttpServletResponse(), this.controller);
运行此测试会导致ModelAttribute(Employee)的值为空

在进行集成测试时,是否有方法将modelattribute对象传递给控制器

谢谢


总结一下:

此问题的解决方案是选择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
路径后的参数。

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

很高兴听到…如果有助于解决问题,请接受答案,以便其他用户会知道……例如,如果员工有一个类型为company的成员“company”(比如说,它有名称和描述字段),您会怎么做?您如何表达到company.name和company.description的路径?很高兴听到…如果答案有助于解决您的问题,请接受答案,以便其他用户知道…例如,如果员工有company类型的成员“company”(比如说,有name和description字段),您会怎么做?如何表达到company.name和company.description的路径?