From ae4ab1708b1ce8028de094d02d29a2fe6fae879e Mon Sep 17 00:00:00 2001 From: Niek Haarman Date: Sun, 27 Mar 2016 14:50:49 +0200 Subject: [PATCH] Account for Class when creating instances. --- .../nhaarman/mockito_kotlin/CreateInstance.kt | 8 ++++++++ .../src/test/kotlin/CreateInstanceTest.kt | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/mockito-kotlin/src/main/kotlin/com/nhaarman/mockito_kotlin/CreateInstance.kt b/mockito-kotlin/src/main/kotlin/com/nhaarman/mockito_kotlin/CreateInstance.kt index 8910770f..8a7cb300 100644 --- a/mockito-kotlin/src/main/kotlin/com/nhaarman/mockito_kotlin/CreateInstance.kt +++ b/mockito-kotlin/src/main/kotlin/com/nhaarman/mockito_kotlin/CreateInstance.kt @@ -37,6 +37,7 @@ import kotlin.reflect.KType import kotlin.reflect.defaultType import kotlin.reflect.jvm.isAccessible import kotlin.reflect.jvm.javaType +import kotlin.reflect.jvm.jvmName /** * A collection of functions that tries to create an instance of @@ -54,6 +55,7 @@ fun createInstance(kClass: KClass): T { kClass.isPrimitive() -> kClass.toDefaultPrimitiveValue() kClass.isEnum() -> kClass.java.enumConstants.first() kClass.isArray() -> kClass.toArrayInstance() + kClass.isClassObject() -> kClass.toClassObject() else -> kClass.easiestConstructor().newInstance() } } @@ -84,6 +86,7 @@ private fun KClass<*>.hasObjectInstance() = objectInstance != null private fun KClass<*>.isMockable() = !Modifier.isFinal(java.modifiers) private fun KClass<*>.isEnum() = java.isEnum private fun KClass<*>.isArray() = java.isArray +private fun KClass<*>.isClassObject() = jvmName.equals("java.lang.Class") private fun KClass<*>.isPrimitive() = java.isPrimitive || !defaultType.isMarkedNullable && simpleName in arrayOf( "Boolean", @@ -124,6 +127,11 @@ private fun KClass.toArrayInstance(): T { } as T } +@Suppress("UNCHECKED_CAST") +private fun KClass.toClassObject(): T { + return Class.forName("java.lang.Object") as T +} + private fun KFunction.newInstance(): T { isAccessible = true return callBy(parameters.associate { diff --git a/mockito-kotlin/src/test/kotlin/CreateInstanceTest.kt b/mockito-kotlin/src/test/kotlin/CreateInstanceTest.kt index b4ce358d..8b8979a5 100644 --- a/mockito-kotlin/src/test/kotlin/CreateInstanceTest.kt +++ b/mockito-kotlin/src/test/kotlin/CreateInstanceTest.kt @@ -27,6 +27,7 @@ import com.nhaarman.expect.expect import com.nhaarman.mockito_kotlin.createInstance import org.junit.Test import java.util.* +import kotlin.reflect.KClass class CreateInstanceTest { @@ -369,6 +370,24 @@ class CreateInstanceTest { expect(result).toNotBeNull() } + @Test + fun classObject() { + /* When */ + val result = createInstance>() + + /* Then */ + expect(result).toNotBeNull() + } + + @Test + fun kClassObject() { + /* When */ + val result = createInstance>() + + /* Then */ + expect(result).toNotBeNull() + } + @Test fun uuid() { /**