我正在尝试测试我的控制器。 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());
}
答案 0 :(得分:0)
尝试使用以下签名作为控制器功能 postUser 。
public View postUser(ModelMap data, @ModelAttribute("profile") @Valid Profile profile, BindingResult bindingResult)
希望这会对你有所帮助。欢呼声。