Set @ModelAttribute in MockHttpServletRequest in J

2019-04-28 15:16发布

问题:

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) { ... }

The Voteobject is defined in the .jsp:

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

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 { ... }

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;
}

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.

回答1:

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");


回答2:

With Spring MVC 3, you can use something along this line:

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