I have a controller that writes to ModelMap as follows:
@Controller @RequestMapping("/dataset") public class DatasetController { @Autowired DatasetDao datasetDao; @RequestMapping(method = RequestMethod.GET) public String getDataset(@RequestParam String name, ModelMap model) { Dataset ds = datasetDao.get(name); model.addAttribute("response", new DatasetResponse(ds)); return "Success"; }
I want to write a test case that receives a dataset and then performs more actions based on its contents. But I am having problems getting data from the service. So far, my test case is:
@Test public void testProducesXml() throws Exception { mockMvc.perform(get("/dataset.xml").param("name", "foo")) .andDo(print()) .andExpect(status().isOk()) .andExpect(model().attribute("Response", hasProperty("name", is("foo")))) .andExpect(xpath("/dataset/name").string("foo")); }
The line model().attribute passes, but the test fails with xpath using:
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.
Ultimately, I would like to get a copy of the DatasetResponse in my test function so that I can do other things with it. I tried using andReturn() , but this fails for the same reason that xpath not working.
It turns out that although there is a DatasetResponse in the model, the response body is empty:
ModelAndView: View name = Success View = null Attribute = Response value = org.vpac.web.model.response.DatasetResponse@457fdd58 errors = [] MockHttpServletResponse: Status = 200 Error message = null Headers = {} Content type = null Body =
However, if I run the application in Tomcat and go to /dataset.xml?name=foo in my browser, I can see the data as XML.
So why is the body empty and how can I get a link to the DatasetResponse ? Edit Do I need to run a view to render a model or something else?
spring spring-mvc unit-testing
z0r
source share