[英]Running code before and after all tests in a surefire execution
我有一個Grizzly HttpServer
,我希望在整個測試組執行期間運行。 另外,我想在測試本身內部從@Rule
與全局HttpServer實例進行交互。
由於我使用Maven Surefire而不是使用JUnit測試套件,我不能在測試套件本身上使用@BeforeClass
/ @AfterClass
。
現在,我能想到的只是懶洋洋地初始化一個靜態字段並從Runtime.addShutdownHook()
停止服務器 - 不好!
有兩種選擇,maven解決方案和surefire解決方案。 最少耦合的解決方案是在pre-integration-test
和post-integration-test
階段執行插件。 請參閱構建生命周期簡介 - 生命周期參考 。 我不熟悉灰熊,但這是一個使用碼頭的例子:
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<configuration>
<contextPath>/xxx</contextPath>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
請注意, start
階段是pre-integration-test
, stop
是post-integration-test
。 我不確定是否有一個灰熊maven插件,但你可以使用maven-antrun-plugin代替。
第二個選項是使用JUnit RunListener 。 RunListener
監聽測試事件,例如測試開始,測試結束,測試失敗,測試成功等。
public class RunListener {
public void testRunStarted(Description description) throws Exception {}
public void testRunFinished(Result result) throws Exception {}
public void testStarted(Description description) throws Exception {}
public void testFinished(Description description) throws Exception {}
public void testFailure(Failure failure) throws Exception {}
public void testAssumptionFailure(Failure failure) {}
public void testIgnored(Description description) throws Exception {}
}
所以你可以聽RunStarted和RunFinished。 這些將啟動/停止您想要的服務。 然后,在surefire中,您可以使用以下命令指定自定義偵聽器:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.10</version>
<configuration>
<properties>
<property>
<name>listener</name>
<value>com.mycompany.MyResultListener,com.mycompany.MyResultListener2</value>
</property>
</properties>
</configuration>
</plugin>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.