在嵌入式Tomcat 7中部署WAR

我目前需要创建一个服务器才能运行多个unit testing。 为了简化这个过程,我想在运行unit testing(使用@BeforeClass表示法)之前将Tomcat嵌入到我的代码中并加载一个Tomcat实例(后者又加载我的WAR文件)。

我的问题是如何将WAR文件部署到嵌入式Tomcat中?

您可能会注意到我无法使用tomcat maven插件,因为我希望它能够与自动化测试一起运行。

此代码适用于Tomcat 8.0:

File catalinaHome = new File("..."); // folder must exist Tomcat tomcat = new Tomcat(); tomcat.setPort(8080); // HTTP port tomcat.setBaseDir(catalinaHome.getAbsolutePath()); tomcat.getServer().addLifecycleListener(new VersionLoggerListener()); // nice to have 

你现在有两个选择。 在catalinaHome/webapps自动部署任何Web应用程序:

 // This magic line makes Tomcat look for WAR files in catalinaHome/webapps // and automatically deploy them tomcat.getHost().addLifecycleListener(new HostConfig()); 

或者您可以手动添加WAR存档。 注意:它们可以位于硬盘上的任何位置。

 // Manually add WAR archives to deploy. // This allows to define the order in which the apps are discovered // plus the context path. File war = new File(...); tomcat.addWebapp("/contextPath", war.getAbsolutePath());