本文介绍了在 JUnit 测试中的 MockHttpServletRequest 中设置 @ModelAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to test a spring mvc controller. One of the methods takes a form input as a POST method.This method gets the form's commandObject through a @ModelAttribute annotation.How can I set this test case up, using Spring's Junit test?

控制器的方法如下所示:

The controller's method looks like this:

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

Vote 对象在 .jsp 中定义:

The Voteobject is defined in the .jsp:

 <form:form method="POST" commandName="vote" name="newvotingform">

现在我想在一个设置如下的测试中测试这个表单POST:

Now I want to test this form POST in a Test which is set up as follows:

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

测试表单POST的实际方法:

The actual method which is testing the form 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 行是使这项工作成功的微弱尝试 - 然而它没有奏效.任何人都可以提供一些提示吗?

The 3 lines which are currently commented out, are feeble attempts to make this work - it did not work however.Can anyone provide some tips on this?

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

I don't really want to call the controllers method directly in my test as I feel like this would not really test the controller in a web context.

推荐答案

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

You have to simulate what your HTML form will do. It will simply pass string request parameters. Try:

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

这篇关于在 JUnit 测试中的 MockHttpServletRequest 中设置 @ModelAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 12:28