Maven で JUnit4 の機能を使った単体テストと結合テスト

結合テストは、以下の方法が一番簡単だが、integration-test フェーズで結合テストが実行されないのが何となく気持ち悪かった。

http://d.hatena.ne.jp/okinaka/20120413/1334292605

以下の記事を参考に、integration-test フェーズにて結合テストが実行できることが確認できた。

http://johndobie.blogspot.co.uk/2012/04/unit-and-integration-tests-with-maven.html

記事中の pom.xml やソースの記述に不備があり、やや手間取った。一度手順を整理しようと思う。

サンプルコード

 svn co https://designbycontract.googlecode.com/svn/trunk/examples/maven/categories
 cd categories
 mvn integration-test

JUnit4 の @Category アノテーション

JUnit4 の @Category アノテーションを使うと、テスト実行時に対象を指定することが出来るとのこと。
http://kentbeck.github.com/junit/javadoc/latest/org/junit/experimental/categories/Category.html

結合テストのカテゴリーを作成。
src/test/java/IntegrationTest.java:

public @interface IntegrationTest {}

@Category をテストケースのクラスに設定。

import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(IntegrationTest.class)
public class ExampleIntegrationTest{
    @Test public void longRunningServiceTest() throws Exception {
    }
}

maven の設定


pom.xml:

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-surefire-plugin</artifactId>
	<version>2.11</version>
	<dependencies>
		<dependency>
			<groupId>org.apache.maven.surefire</groupId>
			<artifactId>surefire-junit47</artifactId>
			<version>2.12</version>
		</dependency>
	</dependencies>
	<configuration>
		<includes>
			<include>**/*.class</include>
		</includes>
		<excludedGroups>IntegrationTest</excludedGroups>
	</configuration>
</plugin>
<plugin>
	<artifactId>maven-failsafe-plugin</artifactId>
	<version>2.12</version>
	<dependencies>
		<dependency>
			<groupId>org.apache.maven.surefire</groupId>
			<artifactId>surefire-junit47</artifactId>
			<version>2.12</version>
		</dependency>
	</dependencies>
	<configuration>
		<groups>IntegrationTest</groups>
	</configuration>
	<executions>
		<execution>
			<goals>
				<goal>integration-test</goal>
			</goals>
			<configuration>
				<includes>
					<include>**/*.class</include>
				</includes>
			</configuration>
		</execution>
	</executions>
</plugin>

ここで、

<groups>IntegrationTest</groups>

の部分が、上記で作成したアノテーション

mavenJUnit のカテゴリー機能を利用するためには、

<dependencies>
	<dependency>
		<groupId>org.apache.maven.surefire</groupId>
		<artifactId>surefire-junit47</artifactId>
		<version>2.12</version>
	</dependency>
</dependencies>

という設定を追加するのがコツとのこと。

maven 実行

mvn integration-test