开发者

Spring MVC: Testing particular annotated method gets invoked

In Spring MVC 3.0, how do I test that a particular method gets invoked?

For example, I have this controller method:

public class myController {
    @RequestMapping(value = 开发者_如何学JAVA"/create", method = RequestMethod.GET)
    public ModelAndView create(ModelMap map) {
            map.put("category", new Category());
            return new ModelAndView("views/someView", map);
        }
}

How do I test that this create() method gets called when somebody requests http://example.com/create url.


In Unit Tests, you should only test your controller's Java code, without using any Servlet technology.

In integration tests you can do one of several things:

Use the org.springframework.mock.web package in the spring-test artifact, which contains Mock Objects for request, response, servletContext to fire fake requests at your controllers and read the data from the fake responses.

Or use a web testing framework like Selenium that works against a deployed webapp.


How do I test that this create() method gets called when somebody requests http://example.com/create url.

Looks really like a integration test. Sean Patrick Floyd already mentioned some ways how to test that, but to my understanding none of this options really tests that a request to an url really invokes the method. -- The mocking way simulates the request and the selenium test tests only the return value, but not the Invocation. -- Don't get my wrong, I believe that this two other tests are in most cases better (easyer to test and even more valid test results), but if you really want to test the invokation I would come up with this solution.

Use a web testing framework like Selenium (or Selenium 2/Webdriver) or only a simple one that only generates HTTP requests. -- To do that tests you will need of curse the deployed application. -- so it is realy an integration test.

To check that the method is invoked. I would recommend to use a logging tool (Log4J). Then use a Tool like AspectJ or Spring AOP Support to add logging statements to your controller method. The logging should be written to some logger that writes to an other destination then the other loggers you use.

At the end the last step is, that you need to verify that the expected logging statement is is the logfile after the test sends the http request. (Pay attention to the fact, that the logging may is asynchronous.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜