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

commonMain.org.kodein.mock.ArgConstraintsBuilder.kt Maven / Gradle / Ivy

There is a newer version: 2.0.0
Show newest version
package org.kodein.mock

import kotlin.reflect.KClass


public class ArgConstraintsBuilder internal constructor(private val references: References) {
    private val constraints: MutableList> = ArrayList()

    internal fun getConstraints(args: Array<*>): List> {
        val list = when {
            constraints.size == args.size -> constraints.toList()
            constraints.isEmpty() -> args.map { if (it == null) ArgConstraint.isNull() else ArgConstraint.isEqual(it) }
            else -> throw Mocker.MockingException("You cannot mix literal values and constraints. Please replace all literal values by their constraint counterpart (isEqual(value) or isNull()).")
        }
        constraints.clear()
        return list
    }

    @PublishedApi
    @Suppress("UNCHECKED_CAST")
    internal fun  toReturn(constraint: ArgConstraint, cls: KClass<*>): T {
        constraints.add(constraint)

        try {
            return references.getReference(cls) as T
        } catch (e: Throwable) {
            throw RuntimeException("Could not find a way to get a reference of ${cls.bestName()}.\n" +
                    "Please open an issue: https://github.com/Kodein-Framework/MocKMP/issues/new\n" +
                    "In the meantime, you can give the mocker a reference to use with mocker.useReference(${cls.simpleName}).", e)
        }
    }

    public inline fun  isAny(capture: MutableList? = null): T = toReturn(ArgConstraint.isAny(capture), T::class)
    public inline fun  isEqual(expected: T, capture: MutableList? = null): T = toReturn(ArgConstraint.isEqual(expected, capture), T::class)
    public inline fun  isNotEqual(expected: T, capture: MutableList? = null): T = toReturn(ArgConstraint.isNotEqual(expected, capture), T::class)
    public inline fun  isSame(expected: T, capture: MutableList? = null): T = toReturn(ArgConstraint.isSame(expected, capture), T::class)
    public inline fun  isNotSame(expected: T, capture: MutableList? = null): T = toReturn(ArgConstraint.isNotSame(expected, capture), T::class)
    public inline fun  isNull(capture: MutableList? = null): T = toReturn(ArgConstraint.isNull(capture), T::class)
    public inline fun  isNotNull(capture: MutableList? = null): T = toReturn(ArgConstraint.isNotNull(capture), T::class)

    public inline fun  isValid(constraint: ArgConstraint): T = toReturn(constraint, T::class)
    @Suppress("UNCHECKED_CAST")
    public inline fun  isValid(capture: MutableList? = null, description: String = "isValid", noinline test: (T) -> ArgConstraint.Result): T = isValid(ArgConstraint(capture, description, test as (Any?) -> ArgConstraint.Result))
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy