2013-07-23 221 views
6

我目前需要創建一個服務器才能運行一些單元測試。爲了簡化這個過程,我想在運行單元測試(使用@BeforeClass表示法)之前,將Tomcat嵌入到我的代碼中並加載一個Tomcat實例(它反過來加載我的WAR文件)。在嵌入式Tomcat中部署WAR 0

我的問題是如何將WAR文件部署到嵌入式Tomcat中?

您可能注意到我無法使用tomcat maven插件,因爲我希望它能夠使用自動化測試運行。

+0

你檢查了[this](https://forums.oracle.com/thread/2348024)嗎? – NREZ

回答

5

該代碼可以使用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 

現在你有兩個選擇。自動部署任何Web應用程序catalinaHome/webapps

// 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());