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

com.oneeyedmen.amock.Expektations.kt Maven / Gradle / Ivy

package com.oneeyedmen.amock

import com.natpryce.hamkrest.MatchResult
import com.natpryce.hamkrest.Matcher
import org.hamcrest.Description
import org.jmock.Expectations
import org.jmock.Sequence
import kotlin.reflect.KClass

@Suppress("unused")
class Expektations: Expectations() {

    inline fun  with(matcher: Matcher): T {
        addParameterMatcher(matcher.asHamcrest())
        return dummyValueOfType(T::class)
    }

    val  T.which: WillThunker get() = WillThunker()

    infix fun  WillThunker.will(action: TypedAction) = super.will(action)

    infix fun  WillThunker.will(block: () -> T) = super.will(invoke("invoke a block", block))

    fun Any?.inSequence(sequence: Sequence) = super.inSequence(sequence)

    @Suppress("unused")
    class WillThunker() // required to make the types work, see http://stackoverflow.com/q/39596420/97777



}

// Yuk yuk yuk yuk yuk
@Suppress("UNCHECKED_CAST", "PLATFORM_CLASS_MAPPED_TO_KOTLIN")
fun  dummyValueOfType(type: KClass<*>): T {
    // See http://stackoverflow.com/q/33987746/97777
    return when(type.java) {
        java.lang.Boolean::class.java-> false as T
        java.lang.Character::class.java-> '\u0000' as T
        else -> (if (Number::class.java.isAssignableFrom(type.java)) 0 else null) as T
    }
}

fun  Matcher.asHamcrest(): org.hamcrest.Matcher {
    return object : org.hamcrest.BaseMatcher() {
        @Suppress("UNCHECKED_CAST")
        override fun matches(item: Any?): Boolean {
            return [email protected](item as T) is MatchResult.Match
        }

        override fun describeTo(description: Description) {
            description.appendText([email protected])
        }
    }
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy