【发布时间】:2011-09-14 10:47:51
【问题描述】:
我正在尝试测试一个 spring mvc 控制器。其中一种方法将表单输入作为 POST 方法。
此方法通过@ModelAttribute 注释获取表单的commandObject。
如何使用 Spring 的 Junit 测试设置此测试用例?
控制器的方法如下所示:
@RequestMapping(method = RequestMethod.POST)
public String formSubmitted(@ModelAttribute("vote") Vote vote, ModelMap model) { ... }
Voteobject 在 .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, res, vc) ;
model = handle.getModelMap();
assert "Test".equals(((Vote) model.get("vote")).getName());
assert ((Vote) model.get("vote")).getState() == Vote.STATE.RUNNING;
}
当前被注释掉的 3 行是使这项工作的微弱尝试 - 但是它没有工作。 任何人都可以提供一些提示吗?
我真的不想在我的测试中直接调用控制器方法,因为我觉得这不会真正在网络环境中测试控制器。
【问题讨论】:
标签: spring spring-mvc junit annotations