在JUnit Test中的MockHttpServletRequest中设置@ModelAttribute

chz*_*gla 6 junit spring annotations spring-mvc

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

控制器的方法如下所示:

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

Vote对象在.jsp中定义:

 <form:form method="POST" commandName="vote" name="newvotingform">
Run Code Online (Sandbox Code Playgroud)

现在我想在Test中测试这个表单POST,其设置如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring/applicationContext.xml"})
@TestExecutionListeners({WebTestExecutionerListener.class, DependencyInjectionTestExecutionListener.class})
public class FlowTest { ... }
Run Code Online (Sandbox Code Playgroud)

测试表单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;
}
Run Code Online (Sandbox Code Playgroud)

目前被评论出来的3条线路都是微弱的尝试 - 但它没有起作用.任何人都可以提供一些提示吗?

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

rjs*_*ang 7

您必须模拟HTML表单的功能.它将简单地传递字符串请求参数.尝试:

req.setParameter("name","Test");
req.setParameter("duration","45");
Run Code Online (Sandbox Code Playgroud)


Yil*_*ing 7

使用Spring MVC 3,您可以使用以下内容:

        mockMvc.perform(post("/secretSauce")
            .param("password", "123")
            .sessionAttr("sessionData", "tomato"))
            .andDo(print())
            .andExpect(status().isOk());
Run Code Online (Sandbox Code Playgroud)