试图将对象传递给控制器​​(Spring MVC)

时间:2012-09-27 13:50:39

标签: spring unit-testing spring-mvc spring-3

我正在尝试测试我的控制器。 Spring填充我的Profile对象但它是空的。我可以在电话之前设置电子邮件,它仍为空。如何以适当的方式jag传递个人资料?

    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("test@mail.com");

            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());


}

1 个答案:

答案 0 :(得分:0)

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

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

希望这会对你有所帮助。欢呼声。