如何解决在JUnit Test的MockHttpServletRequest中设置@ModelAttribute
|| 我正在尝试测试spring mvc控制器。其中一种方法将表单输入作为POST方法。 此方法通过“ 0”批注获取表单的commandObject。 如何使用Spring的Junit测试设置此测试用例? 控制器的方法如下所示:@RequestMapping(method = RequestMethod.POST)
public String formSubmitted(@ModelAttribute(\"vote\") Vote vote,ModelMap model) { ... }
js2ѭ对象在.jsp中定义:
<form:form method=\"POST\" commandName=\"vote\" name=\"newvotingform\">
现在,我要在测试中测试此表单POST,其设置如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {\"classpath:/spring/applicationContext.xml\"})
@TestExecutionListeners({WebTestExecutionerListener.class,DependencyInjectionTestExecutionListener.class})
public class FlowTest { ... }
测试POST形式的实际方法:
@Test
public void testSingleSession() throws Exception {
req = new MockHttpServletRequest(\"GET\",\"/vote\");
res = new MockHttpServletResponse();
handle = adapter.handle(req,res,vc);
model = handle.getModelMap();
assert ((Vote) model.get(\"vote\")).getName() == null;
assert ((Vote) model.get(\"vote\")).getState() == Vote.STATE.NEW;
req = new MockHttpServletRequest(\"POST\",\"/vote\");
res = new MockHttpServletResponse();
Vote formInputVote = new Vote();
formInputVote.setName(\"Test\");
formInputVote.setDuration(45);
// req.setAttribute(\"vote\",formInputVote);
// req.setParameter(\"vote\",formInputVote);
// req.getSession().setAttribute(\"vote\",formInputVote);
handle = adapter.handle(req,vc) ;
model = handle.getModelMap();
assert \"Test\".equals(((Vote) model.get(\"vote\")).getName());
assert ((Vote) model.get(\"vote\")).getState() == Vote.STATE.RUNNING;
}
当前被注释掉的3行是微不足道的尝试来完成这项工作-但是它没有工作。
有人可以提供一些提示吗?
我真的不想在测试中直接调用controllers方法,因为我觉得这不会真正在Web上下文中测试控制器。
解决方法
您必须模拟HTML表单将执行的操作。它将仅传递字符串请求参数。尝试:
req.setParameter(\"name\",\"Test\");
req.setParameter(\"duration\",\"45\");
, 使用Spring MVC 3,您可以沿以下方向使用:
mockMvc.perform(post(\"/secretSauce\")
.param(\"password\",\"123\")
.sessionAttr(\"sessionData\",\"tomato\"))
.andDo(print())
.andExpect(status().isOk());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。