com.github.codefabrikgmbh.scenarios.Given.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of scenarios-kotlin Show documentation
Show all versions of scenarios-kotlin Show documentation
Library for easily writing readable and maintainable integration tests
The newest version!
package com.github.codefabrikgmbh.scenarios
import kotlin.reflect.KClass
fun given(
scenarioSupplier: () -> T,
afterScenario: () -> Unit = {},
executeSteps: T.() -> Unit
): ScenarioRunner {
return ScenarioRunner(scenarioSupplier, afterScenario, executeSteps)
}
class ScenarioRunner(
private val scenarioSupplier: () -> T,
private val afterScenario: () -> Unit,
private val executeSteps: T.() -> Unit
) {
fun run() {
runExpecting(null)
}
@Suppress("UNCHECKED_CAST")
fun runExpecting(expected: KClass?, expectationSteps: T.(K) -> Unit = {}) {
val scenarioResult = runCatching(scenarioSupplier)
scenarioResult.onFailure {
afterScenario()
throw AssertionError("Context is invalid.")
}
val executionResult = scenarioResult.mapCatching(this.executeSteps)
if (expected == null) {
afterScenario()
executionResult.onFailure { throw it }
} else {
executionResult.onSuccess {
afterScenario()
throw AssertionError("Expected error $expected has not been thrown.")
}
executionResult.onFailure { exception ->
if (exception::class != expected) {
afterScenario()
throw exception
}
val expectationResult = scenarioResult.mapCatching { expectationSteps(it, exception as K) }
afterScenario()
expectationResult.onFailure { throw it }
}
}
}
}