新网站建设服务,页面设计是什么专业,网络推广有哪些常用方法,中山建设网站官网在Spring MVC中对控制器进行集成测试的一种方法是使用Spring提供的集成测试支持。 对于Junit4#xff0c;此支持包括一个名为SpringJunit4ClassRunner的自定义Junit Runner和一个用于加载相关Spring配置的自定义批注。 样本集成测试将遵循以下原则#xff1a; RunWith(Spri… 在Spring MVC中对控制器进行集成测试的一种方法是使用Spring提供的集成测试支持。 对于Junit4此支持包括一个名为SpringJunit4ClassRunner的自定义Junit Runner和一个用于加载相关Spring配置的自定义批注。 样本集成测试将遵循以下原则 RunWith(SpringJUnit4ClassRunner.class)
ContextConfiguration(locations{classpath:/META-INF/spring/webmvc-config.xml, contextcontrollertest.xml})
public class ContextControllerTest {Autowiredprivate RequestMappingHandlerAdapter handlerAdapter;Autowiredprivate RequestMappingHandlerMapping handlerMapping;......Testpublic void testContextController() throws Exception{MockHttpServletRequest httpRequest new MockHttpServletRequest(POST,/contexts);httpRequest.addParameter(name, context1);httpRequest.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE,new FlashMap());MockHttpServletResponse response new MockHttpServletResponse();Authentication authentication new UsernamePasswordAuthenticationToken(new CustomUserDetails(..), null);SecurityContextHolder.getContext().setAuthentication(authentication);Object handler this.handlerMapping.getHandler(httpRequest).getHandler();ModelAndView modelAndView handlerAdapter.handle(httpRequest, response, handler);assertThat(modelAndView.getViewName(), is(redirect:/contexts));}
} 我已经使用MockHttpServletRequest创建对“ / contexts” uri的虚拟POST请求并为Controller中可用的Spring Security相关细节添加了一些身份验证细节。 正在验证控制器返回的ModelAndView以确保返回的视图名称符合预期。 执行与控制器相关的集成的更好方法是使用一个相对较新的Spring项目Spring-test-mvc 该项目提供了一种流畅的方法来测试控制器流。 使用Spring-test-mvc与上述相同的测试如下所示 Test
public void testContextController() throws Exception{Authentication authentication new UsernamePasswordAuthenticationToken(new CustomUserDetails(..), null);SecurityContextHolder.getContext().setAuthentication(authentication);xmlConfigSetup(classpath:/META-INF/spring/webmvc-config.xml, classpath:/org/bk/lmt/web/contextcontrollertest.xml).build().perform(post(/contexts).param(name, context1)).andExpect(status().isOk()).andExpect(view().name(redirect:/contexts));
} 现在测试变得更加简洁无需直接处理MockHttpServletRequest和MockHttpServletResponse实例并且读取效果很好。 我对静态导入的数量和此处涉及的函数调用的数量有所保留但是与其他所有内容一样这只是适应这种测试方法的问题。 WEB-INF位置下的资源也可以通过以下方式与spring-test-mvc一起使用 xmlConfigSetup(/WEB-INF/spring/webmvc-config.xml,classpath:/org/bk/lmt/web/contextcontrollertest.xml).configureWebAppRootDir(src/main/webapp, false).build().perform(post(/contexts).param(name, context1)).andExpect(status().isOk()).andExpect(view().name(redirect:/contexts));xmlConfigSetup(/WEB-INF/spring/webmvc-config.xml, classpath:/org/bk/lmt/web/contextcontrollertest.xml).configureWebAppRootDir(src/main/webapp, false).build().perform(get(/contexts)).andExpect(status().isOk()).andExpect(view().name(contexts/list)); 参考 all和其他博客中的JCG合作伙伴 Biju Kunjummen提供的Spring MVC集成测试 。 翻译自: https://www.javacodegeeks.com/2012/07/spring-mvc-integration-tests.html