开发者

Spring 3 - Testing a controller @ModelAttribute method

开发者 https://www.devze.com 2023-02-08 02:22 出处:网络
I am trying to test a controller with this method: @RequestMapping(value=\"/export-csv\") public ModelAndView exportCSV(@ModelAttribute(\"gsscModel\") GsscModel gsscModel) {

I am trying to test a controller with this method:

@RequestMapping(value="/export-csv")    
public ModelAndView exportCSV(@ModelAttribute("gsscModel") GsscModel gsscModel) {

And I would like to know how can I create a unit testing for testing this. At the moment I am using:

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/support/export-csv");
    //request.setMethod("GET");
    new AnnotationMethodHandlerAdapter().handle(request, 
  开发者_开发百科          new MockHttpServletResponse(), this.controller);

However I always get the following error:

org.springframework.web.HttpSessionRequiredException: Session attribute 'gsscModel' required - not found in session

I've been trying to find info about this on the documentation, but haven't found anything.

Thanks


To re-iterate my comments, I suggest that you're not unit testing your code properly. One of the benefits of the Spring 3 annotation approach is that it makes unit testing considerably easier, since there's generally no need to mess about with mock request and response objects.

In your case, your unit test can invoke the exportCSV method directly, and handle the returned ModelAndView appropriately. There's really no need to use infrastructure classes like AnnotationMethodHandlerAdapter to invoke the method for you, that just complicates things.

0

精彩评论

暂无评论...
验证码 换一张
取 消