在JUnit测试的MockHttpServletRequest中设置@ModelAttribute


问题内容

我正在尝试测试Spring
MVC控制器。其中一种方法将表单输入作为POST方法。此方法通过@ModelAttribute注释获取表单的commandObject
。如何使用Spring的Junit测试设置该测试用例?

控制器的方法如下所示:

@RequestMapping(method = RequestMethod.POST)
public String formSubmitted(@ModelAttribute("vote") Vote vote, ModelMap model) { ... }

Vote对象在.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行是微不足道的尝试来完成这项工作-但是它没有工作。有人可以提供一些提示吗?

我真的不想在测试中直接调用controllers方法,因为我觉得这不会真正在Web上下文中测试控制器。


问题答案:

您必须模拟HTML表单将执行的操作。它将仅传递字符串请求参数。尝试:

req.setParameter("name","Test");
req.setParameter("duration","45");