All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.codefabrikgmbh.scenarios.Given.kt Maven / Gradle / Ivy

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 }
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy