2012-09-27 94 views
0

我试图测试我的控制器。 Spring会填充我的Profile对象,但它是空的。我可以在通话之前设置电子邮件地址,但它仍然为空。如何以正确的方式传递一个配置文件?尝试将对象传递给控制器​​(Spring MVC)

private MockHttpServletRequest request; 
    private MockHttpServletResponse response; 

    @Autowired 
    private RequestMappingHandlerAdapter handlerAdapter; 

    @Autowired 
    private RequestMappingHandlerMapping handlerMapping; 

    @Before 
    public void setUp() throws Exception { 
     this.request = new MockHttpServletRequest(); 
     request.setContentType("application/json"); 
     this.response = new MockHttpServletResponse(); 
    } 

    @Test 
    public void testPost() { 
     request.setMethod("POST"); 
     request.setRequestURI("/user/"); // replace test with any value 

     final ModelAndView mav; 
     Object handler; 

     try { 

      Profile p = ProfileUtil.getProfile(); 
      p.setEmail("[email protected]"); 

      request.setAttribute("profile", p); 

      System.out.println("before calling the email is " + p.getEmail()); 

      handler = handlerMapping.getHandler(request).getHandler(); 
      mav = handlerAdapter.handle(request, response, handler); 
      Assert.assertEquals(200, response.getStatus()); 
      // Assert other conditions. 
     } catch (Exception e) { 

     } 
    } 

这是控制器

@RequestMapping(value = "/", method = RequestMethod.POST) 
public View postUser(ModelMap data, @Valid Profile profile, BindingResult bindingResult) { 

    System.out.println("The email is " + profile.getEmail()); 


} 

回答

0

尝试使用以下签名的控制器功能postUser

public View postUser(ModelMap data, @ModelAttribute("profile") @Valid Profile profile, BindingResult bindingResult) 

希望这可以帮助你。干杯。

相关问题