繁体   English   中英

如何在没有控制器类的情况下对Spring MVC拦截器进行单元测试

[英]How to unit test spring mvc interceptors without controller class

我正在尝试在spring-mvc rest应用程序中为其中一个拦截器编写单元测试。 我在用:

- TestNG 6.8.7
- Mockito 1.9.5
- Spring 4.0.0

是否必须让控制器对拦截器进行单元测试? 我们可以在不编写控制器的情况下编写单元测试吗?

谢谢,NN

假设您的意思是HandlerInterceptor

是否必须让控制器对拦截器进行单元测试?

不可以。单元测试应尽可能地独立。 如果您正在对HandlerInterceptor实现进行单元测试,则涉及的仅是您的实现及其所有依赖项。

我们可以在不编写控制器的情况下编写单元测试吗?

是。 HandlerInterceptor只是具有三(3)个方法的接口。 这些方法都不需要控制器,因此您不需要控制器。

是否必须让控制器对拦截器进行单元测试?

不,这不对!

我们可以在不编写控制器的情况下编写单元测试吗?

是。 您可以! , 如下所示。

  1. 设置Web应用程序上下文。
  2. 获取处理程序映射bean。
  3. 获取处理程序执行链。
  4. 遍历拦截器并调用preHandle方法。
  5. 调用控制器的handleRequest方法。
  6. 遍历拦截器并调用postHandle方法。

    受保护的void setUp()引发异常{super.setUp();

      String[] configFiles = new String[] { "file:///c:/abc.xml", }; /* * Ref: http://www.koders.com/java/fid78745323A147B238F4B366225C31603C6F87CE75.aspx?s=%22Seth+Ladd%22 */ MockServletContext sctx = new MockServletContext(""); ctx = new XmlWebApplicationContext(); ctx.setServletContext(sctx); ctx.setConfigLocations(configFiles); ctx.refresh(); } private void testRequest(HttpServletRequest request, HttpServletResponse response){ try { MockHttpServletRequest request = new MockHttpServletRequest("GET","/urlpath/soemname"); MockHttpServletResponse response = new MockHttpServletResponse(); request.setServerName("www.domainname.com"); HandlerMapping handlerMapping = (HandlerMapping) this.getCtx().getBean("beanname"); HandlerExecutionChain hec = handlerMapping.getHandler(request); Controller handler = (Controller) hec.getHandler(); HandlerInterceptor interceptors[] = hec.getInterceptors(); /* * Calling preHandle on interceptors */ for(int i=0; i < interceptors.length; i++){ interceptors[i].preHandle(request, response, handler); } /* * calling the controller handleRequest */ ModelAndView modelAndView = handler.handleRequest(request, response); /* * Calling postHandle on interceptors */ for(int i=0; i < interceptors.length; i++){ interceptors[i].postHandle(request, response, handler, modelAndView); } /* * Validating the response */ } catch (Exception e) { e.printStackTrace(); fail(); } } 

资料来源: http : //forum.spring.io/forum/spring-projects/web/43787-testing-handlerinterceptors-and-controllers

希希尔

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM