我想使用 springs MockMVC 工具编写集成测试:
MockMvcBuilders.webAppContextSetup(...).build();
阅读可用文档http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#spring-mvc-test-framework留下一个问题:如何设置测试对于以编程方式创建的 WebApplicationContext?
如果我正确理解了模拟 mvc 测试的概念,它会神奇地发现一个 servlet 上下文,其中包含调度程序 servlet 和一个用于设置的 WebApplicationContext。目前,我手动创建 WebApplicationContext 并将 DispatcherServlet 添加到码头实例。我想我必须以某种方式解耦?
我想使用 SpringWebConfiguration.class 中定义的 Web 上下文并模拟 SpringConfiguration.class 中定义的根上下文中的所有内容
public static void main(String[] args) throws Exception {
SimpleCommandLinePropertySource ps = new SimpleCommandLinePropertySource(args);
ApplicationContext rootContext = createRootContext(ps);
//start jetty
Server server = new Server(Integer.parseInt(ps.getProperty("port")));
ServletContextHandler contextHandler = new ServletContextHandler();
contextHandler.setContextPath("/");
createWebContext(rootContext, contextHandler);
server.setHandler(contextHandler);
server.start();
server.join();
}
private static ApplicationContext createRootContext(PropertySource propertySource) {
AnnotationConfigApplicationContext rootContext = new AnnotationConfigApplicationContext();
rootContext.getEnvironment().getPropertySources().addFirst(propertySource);
rootContext.register(SpringConfiguration.class); //main configuration class for all beans
rootContext.refresh();
return rootContext;
}
public static WebApplicationContext createWebContext(ApplicationContext rootContext) {
AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
webApplicationContext.setParent(rootContext);
webApplicationContext.register(SpringWebConfiguration.class);
return webApplicationContext;
}
private static WebApplicationContext createWebContext(ApplicationContext rootContext, ServletContextHandler servletContext) throws ServletException {
WebApplicationContext webApplicationContext = createWebContext(rootContext);
/* enable logging of each http request */
servletContext.addFilter(LoggingFilterChain.class, "/*", EnumSet.of(DispatcherType.REQUEST));
registerDispatcherServlet("api", servletContext, webApplicationContext);
return webApplicationContext;
}
private static DispatcherServlet registerDispatcherServlet(String path, ServletContextHandler servletContext, WebApplicationContext ctx) {
DispatcherServlet servlet = new DispatcherServlet(ctx);
servletContext.addServlet(new ServletHolder(servlet), "/" + path + "/*");
return servlet;
}
知道如何更改配置才能使用 mockmvc 测试吗?我更喜欢没有 spring.xml / web.xml 的解决方案。