Testing Spring @MVC annotations

前端 未结 3 454
执念已碎
执念已碎 2021-02-02 03:08

I ran into a problem the other day where a @Valid annotation was accidentally removed from a controller class. Unfortunately, it didn\'t break any of our tests. None of our un

3条回答
  •  天涯浪人
    2021-02-02 03:33

    Sure. There's no reason why your test can't instantiate its own DispatcherServlet, inject it with the various items which it would have in a container (e.g. ServletContext), including the location of the context definition file.

    Spring comes with a variety of servlet-related MockXYZ classes for this purpose, including MockServletContext, MockHttpServletRequest and MockHttpServletResponse. They're not really "mock" objects in the usual sense, they're more like dumb stubs, but they do the job.

    The servlet's test context would have the usual MVC-related beans, plus your beans to test. Once the servlet is initialized, create the mock requests and responses, and feed them into the servet's service() method. If request gets routed correctly, you can check the results as written to the mock response.

提交回复
热议问题