Kotest ソフトアサーション(Soft Assertions)

Soft Assertions は assertSoftly 関数を使って複数のアサーションをまとめて実行するために使用する。

ソフトアサーション

ソフトアサーションを使うと、複数のアサーションをまとめて実行し、失敗を一度に報告できる。最初の失敗で止めるのではなく、失敗した条件をすべて確認したい場合に便利である。

assertSoftly {
    foo shouldBe bar
    foo should contain(baz)
}

これは JUnit の assertAll と似ている。

assertSoftly に対象を渡すこともできる。ブロック内では、その対象に対してアサーションを実行する。

assertSoftly(foo) {
    shouldNotEndWith("b")
    length shouldBe 3
}

例:

import io.kotest.assertions.assertSoftly
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe

class SoftAssertionTest : FunSpec({
    test("soft assertions") {
        val person = Person("devkuma", 30)

        assertSoftly(person) {
            name shouldBe "devkuma"
            age shouldBe 30
        }
    }
})

data class Person(val name: String, val age: Int)

プロジェクト設定を通じて、すべてのテストにソフトアサーションを暗黙的に適用するようにも構成できる。


参照