extractSubject

fun <T> Expect<T>.extractSubject(failureDescription: String? = null, assertionCreator: Expect<T>.(T) -> Unit): Expect<T>(source)

Extracts the subject of this Expect in case it is defined and passes it to the given assertionCreator or adds a failing assertion to this Expect in case the subject is absent (e.g. due to a previous extraction failure).

Return

an Expect for the subject of this expectation.

Since

1.2.0

Parameters

failureDescription

The description used in case the subject is absent - if null is given, then the default failure description is used

assertionCreator

The assertion-creator lambda which is responsible to create and append at least 1 assertion to this Expect.

Samples

val persons = dataGenerator.getRandomPersonsWithChildren()
expect(persons).toHaveElementsAndAll {
    extractSubject { person ->
        feature { f(it::children) }.notToHaveElementsOrAll {
            because("person should at least be 16 years older than its children") {
                feature { f(it::age) }.toBeLessThan(person.age - 16)
            }
        }
    }
}
// imagine the data generator should not return an empty list
val persons = dataGenerator.getRandomPersonsHasABugReturnsEmptyList()
fails { // because persons is empty
    expect(persons).toHaveElementsAndAll { // fails
        // hence the sub-expectations within extractSubject cannot be evaluated
        // and instead we show the custom failure description
        extractSubject("no person defined, cannot extract subject") { person ->
            feature { f(it::children) }.notToHaveElementsOrAll {
                because("person should at least be 16 years older than its children") {
                    feature { f(it::age) }.toBeLessThan(person.age - 16)
                }
            }
        }
    }
}