Set @ModelAttribute to MockHttpServletRequest in JUnit Test

I am trying to test spring mvc controller. One of the methods takes the form of input as a POST method. This method gets the commandObject form using the @ModelAttribute annotation. How can I install this test case using the Junit spring test?

The controller method is as follows:

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

Vote object is defined in .jsp:

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

Now I want to test this form of POST in a test that is configured as follows:

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

The actual method that validates the form of 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 that are currently commented out are weak attempts to do this work - however, it does not work. Can anyone give some advice on this?

I really do not want to call the controller method directly in my test, as I feel that it will not check the controller in the web context.

+6
source share
2 answers

You must mimic what your HTML form will do. It will simply pass the query string parameters. Try:

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

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

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

Source: https://habr.com/ru/post/890466/


All Articles