0

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

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


}
4

1 回答 1

0

尝试对控制器函数postUser使用以下签名。

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

希望这对您有所帮助。干杯。

于 2012-09-28T05:33:54.100 回答