junitの動的生成¶
junit4を利用してjunitのテストケースを動的に作成することでCSVやExcel等の一覧からテストケースを作成し試験を実施することができます。
環境構築¶
junit4が利用できれば利用できるののでmavenの依存性にjunit4を追加します。
pom.xml 追加部分
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency>
pom.xml 全体イメージ
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>jp.dip.snowsaber</groupId> <artifactId>junit-dynamically-generated-exsample</artifactId> <version>0.0.1-SNAPSHOT</version> <!-- 定数定義 --> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project>
基本的な考え方¶
「org.junit.runner.Runner」を継承してクラスを作成します。
コンストラクタを「Class<?> testClass」を引数として作成します。
またRunnerクラスを継承すると以下の2つのメソッドを定義する必要があります。
getDescription
テストケースやテストスイートの情報を取得するためのメソッドとなります。
戻り値の情報を生成する場合には「Description」クラスの「createTestDescription」「createSuiteDescription」を利用します。
createTestDescription
テストを作成する場合に利用します。
createSuiteDescription
テストスィートを作成する場合に利用します。
run
実際にテストを実行するためのメソッドとなります。
作成例
package jp.dip.snowsaber; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.notification.RunNotifier; /** * 動的なテストケース用クラス * * @author snowhiro * */ public class DynamicallyGeneratedTestRunner extends Runner { private Description suite; public DynamicallyGeneratedTestRunner(Class<?> testClass) { suite = Description.createSuiteDescription("管理用のテストスィート"); for (int i = 0; i <10; i++) { suite.addChild(Description.createTestDescription("テストクラス", "cast-" + i)); } } @Override public Description getDescription() { System.out.println("getDescription start"); return suite; } @Override public void run(RunNotifier notifier) { System.out.println("run start"); } }
起動用のクラスを作成します。1で作成したクラスを起動するには「@RunWith」を利用して起動します。クラスの中身は特に記載は不要です。
package jp.dip.snowsaber; import org.junit.runner.RunWith; @RunWith(DynamicallyGeneratedTestRunner.class) public class DynamicallyGeneratedStartingPoint { }
実際に実行してみます。
参考サイト¶
テストケースを動的に生成してJUnitで実行する