Kotest 인스펙터(Inspectors)

Kotest는 Matcher 외에도 Matcher와 관련된 인스펙터라는 개념을 지원한다. 인스펙터는 컬렉션 함수에 대한 확장 함수로, 주어진 단언문이 컬렉션 원소 중 어떤 그룹에 대해 성립하는지 검증할 수 있다.

Inspectors

인스펙터(Inspectors)를 사용하면 컬렉션의 요소를 테스트할 수 있다. 인스펙터는 컬렉션 및 배열의 확장 함수로, 모든 요소 또는 일부 요소가 주어진 단언문을 통과하는지 테스트한다.

예를 들어, 이름 목록에 길이가 7 이상인 요소가 두 개 이상 포함되어 있는지 테스트하려면 이렇게 하면 된다:

val xs = listOf("dev", "gareth", "timothy", "muhammad")
xs.forAtLeast(2) {
    it.shouldHaveMinLength(7)
}

비슷하게 컬렉션의 어떤 요소도 단언문을 통과하지 못했다고 주장하고 싶다면 다음과 같이 할 수 있다:

xs.forNone {
    it.shouldContain("x")
    it.shouldStartWith("bb")
}

전체 검사자 목록은 다음과 같다:

인스펙터 설명
forAll 모든 요소가 단언문을 통과했는지 검사한다.
forNone 어떤 요소도 단언문을 통과 못하는 검사한다.
forOne 단 하나의 요소만 통과했는지 검사한다.
forAtMostOne 0 또는 1개의 요소가 통과했는지 검사한다.
forAtLeastOne 1개 이상의 요소가 통과했는지 검사한다.
forAtLeast(k) k개 이상의 요소가 통과했는지 검사한다.
forAtMost(k) k개 이하의 요소가 통과했는지 검사한다.
forAny forAtLeastOne의 별칭이다.
forSome 1에서 n-1 사이의 요소가 통과했는지 검사한다. 즉, NONE이 통과하거나 ALL이 통과하면 실패로 간주한다.
forExactly(k) 정확히 k개의 요소가 통과했는지 검사한다. 이는 다른 메서드의 구현을 위한 기초이다.

다음을 사용 예제이다.

import io.kotest.core.spec.style.StringSpec
import io.kotest.inspectors.forAll
import io.kotest.inspectors.forAny
import io.kotest.inspectors.forAtLeast
import io.kotest.inspectors.forAtLeastOne
import io.kotest.inspectors.forAtMost
import io.kotest.inspectors.forAtMostOne
import io.kotest.inspectors.forExactly
import io.kotest.inspectors.forNone
import io.kotest.inspectors.forOne
import io.kotest.inspectors.forSome
import io.kotest.matchers.ints.shouldBeGreaterThanOrEqual
import io.kotest.matchers.shouldBe

class NumbersTestWithInspectors : StringSpec({
    val numbers = Array(10) { it + 1 }

    "all are non-negative" { numbers.forAll { it shouldBeGreaterThanOrEqual 0 } }

    "none is zero" { numbers.forNone { it shouldBe 0 } }

    "a single 10" { numbers.forOne { it shouldBe 10 } }

    "at most one 0" { numbers.forAtMostOne { it shouldBe 0 } }

    "at least one odd number" { numbers.forAtLeastOne { it % 2 shouldBe 1 } }

    "at most five odd numbers" { numbers.forAtMost(5) { it % 2 shouldBe 1 } }

    "at least three even numbers" { numbers.forAtLeast(3) { it % 2 shouldBe 0 } }

    "some numbers are odd" { numbers.forAny { it % 2 shouldBe 1 } }

    "some but not all numbers are even" { numbers.forSome { it % 2 shouldBe 0 } }

    "exactly five numbers are even" { numbers.forExactly(5) { it % 2 shouldBe 0 } }
})

참조




최종 수정 : 2024-04-23