Kotest Reflective Arbs

JVM でテストを実行するとき、Kotest はより複雑な Arb を自動生成する機能をサポートする。

Reflective Arbs

JVM でテストを実行するとき、Kotest はより複雑な Arb を自動生成する機能をサポートする。生成された Arb は、組み込みの基本 Arb と追加の reflective Arb を使用してクラスパラメータを埋める。生成とインスタンス化だけが必要で、フィルタリングが不要な場合は、checkAll/forAll 呼び出しでクラス型を直接使用できる。追加の操作や無効な値をフィルタリングするために Arb を取得したい場合は、型引数付きで Arb.bind を使用して Arb を取得できる。必要な型がデフォルトでサポートされていない型に依存する場合は、Arb.bind を呼び出すときにその型の Arb を提供できる。

例:

enum class Currency {
  USD, GBP, EUR
}

class CurrencyAmount(
  val amount: Long,
  val currency: Currency
)

context("Currencies converts to EUR") { // In some spec
  checkAll(Arb.bind<CurrencyAmount>().filter { it.currency != EUR }) { currencyAmount ->
    val converted = currencyAmount.convertTo(EUR)
    converted.currency shouldBe EUR
  }
}

context("Converting to a currency and back yields the same amount") { // In some spec
  checkAll<CurrencyAmount, Currency>() { currencyAmount, currency ->
    val converted = currencyAmount.convertTo(currency).convertTo(currencyAmount.currency)
    converted.currency shouldBe currencyAmount.currency
  }
}

リフレクションによるバインディングは次をサポートする。

  • private ではないクラスまたはデータクラスで、プライマリコンストラクタが private ではなく、コンストラクタパラメータもサポートされる型である場合。
  • Pair。1 と 2 がこのカテゴリに属する場合。
  • プリミティブ。
  • enum。
  • sealed class。サブタイプとそのプライマリコンストラクタは private であってはならない。
  • java.timeLocalDateLocalDateTimeLocalTimePeriodInstant
  • BigDecimalBigInteger
  • コレクション(SetListMap)。
  • 提供された Arbs を通じて Arb が提供されたクラス。

参照