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);
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.
source share