結合テストなどは条件付きで実行を切り替えたい場合がある。JUnit 5の条件付き実行を行うanntationがあるのでこれを使用できる。また、gradleからそのannotationがついたテストケースを実行する方法にも触れる。
- gradle 8.6
- junit-jupiter:5.10.3
ソースコード
環境変数の場合。
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
@EnabledIfEnvironmentVariable(named = "testing.type", matches = "IT")
class SomeIntegrationTest1 {
...
システムプロパティの場合。
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
@EnabledIfSystemProperty(named = "testing.type", matches = "IT")
public class SomeIntegrationTest2 {
...
gradleから上記のテストケースを実行するには、それぞれの方法で値をセットするtaskを作成する。
環境変数の場合。
tasks.register("integrationTest", Test) {
environment("testing.type", "IT")
useJUnitPlatform()
}
システムプロパティの場合。
tasks.register("integrationTest", Test) {
systemProperty("testing.type", "IT")
useJUnitPlatform()
}
コマンドライン引数などから指定したい場合、それに応じた手段で取得した値を上記のように設定すればよい。以下はその一例。
tasks.register("integrationTest", Test) {
systemProperty("testing.type", System.getProperty('testing.type'))
useJUnitPlatform()
}
ハマった点
以下のようにしても意図通りの結果にはならない。下記で指定している-D
はgradleに対するパラメータなため。
gradle test -Dtesting.type=IT