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

jvmMain.io.mockk.impl.instantiation.JvmMockFactory.kt Maven / Gradle / Ivy

There is a newer version: 1.13.12
Show newest version
package io.mockk.impl.instantiation

import io.mockk.InternalPlatformDsl.toStr
import io.mockk.MockKException
import io.mockk.impl.stub.MockKStub
import io.mockk.impl.stub.Stub
import io.mockk.impl.stub.StubGatewayAccess
import io.mockk.impl.stub.StubRepository
import io.mockk.proxy.MockKAgentException
import io.mockk.proxy.MockKProxyMaker
import kotlin.reflect.KClass

class JvmMockFactory(
    val proxyMaker: MockKProxyMaker,
    instantiator: JvmInstantiator,
    stubRepository: StubRepository,
    gatewayAccess: StubGatewayAccess
) :
    AbstractMockFactory(
        stubRepository,
        instantiator,
        gatewayAccess
    ) {

    @Suppress("UNCHECKED_CAST")
    override fun  newProxy(
        cls: KClass,
        moreInterfaces: Array>,
        stub: Stub,
        useDefaultConstructor: Boolean,
        instantiate: Boolean
    ): T {
        return try {
            val proxyResult = proxyMaker.proxy(
                cls.java,
                moreInterfaces.map { it.java }.toTypedArray(),
                JvmMockFactoryHelper.mockHandler(stub),
                useDefaultConstructor,
                null
            )

            (stub as? MockKStub)?.disposeRoutine = proxyResult::cancel

            proxyResult.get()
        } catch (ex: MockKAgentException) {
            when {
                instantiate -> {
                    log.trace(ex) {
                        "Failed to build proxy for ${cls.toStr()}. " +
                                "Trying just instantiate it. " +
                                "This can help if it's last call in the chain"
                    }

                    gatewayAccess.anyValueGenerator().anyValue(cls, isNullable = false) {
                        instantiator.instantiate(cls)
                    } as T
                }

                useDefaultConstructor ->
                    throw MockKException("Can't instantiate proxy via " +
                        "default constructor for $cls", ex)

                else ->
                    throw MockKException("Can't instantiate proxy for $cls", ex)
            }
        }
    }
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy