為さねば成らぬ

retia.verno@gmail.com

Junit5を導入する

GitHub - mannodermaus/android-junit5: Testing with JUnit 5 for Android.

build.gradleに入れるだけ。

// build.gradle
buildscript {
  dependencies {
    classpath "de.mannodermaus.gradle.plugins:android-junit5:1.2.0.0"
  }
}
// app/build.gradle
apply plugin: "de.mannodermaus.android-junit5"

dependencies {
  // (Required) Writing and executing Unit Tests on the JUnit Platform
  testImplementation "org.junit.jupiter:junit-jupiter-api:5.2.0"
  testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.2.0"

  // (Optional) If you need "Parameterized Tests"
  testImplementation "org.junit.jupiter:junit-jupiter-params:5.2.0"

  // (Optional) If you also have JUnit 4-based tests
  testImplementation "junit:junit:4.12"
  testRuntimeOnly "org.junit.vintage:junit-vintage-engine:5.2.0"
}

実際のテストコードはこちら。

class Test{
  @BeforeEach
  fun init(){
  }

  @Test
  fun test1(){
  }

  @Nested
  inner class HogeTest{
    @BeforeEach
    fun init(){
    }
  
    @Test
    fun test2(){
    }
  }
}

Junit4からJunit5へのmigrationで気をつけるのが

@Test

Junit4にもTestアノテーションがあるが、Junit5だとpackageが別。(org.junit.jupiter.api.Test) 間違っているとテストとして認識されない。

@BeforeEach

@Beforeは@BeforeEachへ変わっている。

JUnit5で一番良い(というかこれのために使っている)のは@Nested。 @Nestedをつけたinner classに含まれる@Testもテストが走るようになり、複数階層の入れ子が可能。 構造的にテストが書けるのでだいぶわかりやすくなる。 t-wadaさんのTDDワークショップ受けた時にテストを構造的に書くことの重要性を知ったので、@Nestedが入ってほんとよかった。