【问题标题】:Set @ModelAttribute in MockHttpServletRequest in JUnit Test在 JUnit 测试中的 MockHttpServletRequest 中设置 @ModelAttribute
【发布时间】: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


    【解决方案1】:

    你必须模拟你的 HTML 表单会做什么。它只会传递字符串请求参数。试试:

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

    【讨论】:

      【解决方案2】:

      使用 Spring MVC 3,您可以使用以下方法:

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

      【讨论】:

      • 我会使用flashAttr("vote", new Vote()) 而不是sessionAttr()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      相关资源
      最近更新 更多