Site cover image

fhhm’s blog

Tableでテストを書く

同じ処理を異なるインプットでテストしたいときにTableを使うとスッキリ書ける。

複数のエラーを返しうるメソッドなどのテストでよく使う。

import org.scalatest.GivenWhenThen
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.prop.TableDrivenPropertyChecks._
import org.scalatest.matchers.should.Matchers._

class SampleTest extends AnyFunSuite with GivenWhenThen {
  
  val testCases =
    Table(
      ("expected", "input", "description"),
      (false, 1),
      (true, 2),
      (false, 3)
    )

  forAll(testCases) { (expected: Boolean, input: Int, _) =>
    val result = input % 2 == 0
    assertResult(expected)(result)
  }
}