2010-02-03 68 views
10

我有一個Maven項目,啓動一個用於預集成測試(jUnit測試)的Tomcat容器。我的大多數測試都要求重新啓動測試下的Web應用程序。所以我想在每個jUnit測試執行之前重新啓動Tomcat容器。如何使用Java啓動和停止Tomcat容器?

至於現在我使用cargo-maven2-plugin來配置tomcat容器。

那麼,是否有可能用java語句啓動和停止容器?

+1

您確定需要重新啓動容器,而不是重新加載webapp? – 2010-02-03 07:47:04

回答

14

那麼,有可能用java語句啓動和停止容器?

您的用例看起來非常奇怪(必須在測試之間重新啓動容器),但我們不要討論這一點。要回答你的問題,是的,這是可能的,這可以使用Cargo的Java API來完成。

要啓動Tomcat容器和部署你的戰爭,你可以做這樣的事情在setUp()方法:

// (1) Optional step to install the container from a URL pointing to its distribution 
Installer installer = new ZipURLInstaller(new URL("http://www.apache.org/dist/tomcat/tomcat-6/v6.0.20/bin/apache-tomcat-6.0.20.zip")); 
installer.install(); 

// (2) Create the Cargo Container instance wrapping our physical container 
LocalConfiguration configuration = (LocalConfiguration) new DefaultConfigurationFactory() 
     .createConfiguration("tomcat6x"), ContainerType.INSTALLED, ConfigurationType.STANDALONE); 
container = (InstalledLocalContainer) new DefaultContainerFactory() 
     .createContainer("tomcat6x", ContainerType.INSTALLED, configuration); 
container.setHome(installer.getHome()); 

// (3) Statically deploy some WAR (optional) 
WAR deployable = new WAR("./webapp-testing-webapp/target/webapp-testing-webapp-1.0.war"); 
deployable.setContext("ROOT"); 
configuration.addDeployable(deployable); 

// (4) Start the container 
container.start(); 

而在tearDown()方法停止它。

// (6) Stop the container 
container.stop(); 
+0

謝謝,沒有想到這個貨物。 – 2010-02-04 02:39:36

+0

@Vinegar通過插件使用Cargo更爲常見(至少我認爲是這樣),但Cargo *實際上是一個Java API。這可以很方便(越來越多的容器提供嵌入式API,但Cargo's API是「統一的」)。 – 2010-02-04 11:17:37

+0

是的,我傾向於同意。謝謝。 – 2010-02-04 11:42:12

1

是的。但我很無聊,你的測試需要多長時間。您必須修復測試以不依賴服務器啓動和關閉。它可以在容器內運行測試,但容器應該在測試前啓動一次。

那麼回答你的問題,你可以使用系統調用從Java執行相關的.sh.bat文件。類似下面,

Runtime r = Runtime.getRuntime(); 
Process p = r.exec("start.sh"); 
p.waitFor(); 
5

bootstrap.jar並從Tomcat \ bin添加到您的類路徑和下面的摘錄可以幫助共享記錄-API-1.1.1,

Bootstrap bootstrap=new Bootstrap(); 
bootstrap.setCatalinaHome("D:/apache-tomcat-5.5.28"); 

bootstrap.start(); 

Thread.sleep(60000); 

bootstrap.stop(); 
2

我使用如下方法:

private static final String TOMCAT = "D:/test_tomcat"; 
@BeforeClass 
public static void runTomcat() { 
    bootstrap = new Bootstrap(); 
    bootstrap.setCatalinaHome(TOMCAT); 
    try { 
     bootstrap.start();   
    } catch (Exception e) { 
     e.printStackTrace(); 
     fail("Не удалось запустить Tomcat"); 
    } 
} 

@AfterClass 
public static void stopTomcat() { 
    try { 
     bootstrap.stop(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

不過是方法有一個問題 - 我需要每次複製WAR文件「的webapps」目錄中有變化的源代碼。 我在web-inf的classpath中複製了我的類,並從web-inf/lib中的classpath複製了'jar'。