Skip to content

Commit

Permalink
Merge pull request #28 from nhaarman/create-class-objects
Browse files Browse the repository at this point in the history
Account for Class<T> when creating instances.
  • Loading branch information
nhaarman committed Mar 27, 2016
2 parents a013a48 + ae4ab17 commit 129f9e6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -54,6 +55,7 @@ fun <T : Any> createInstance(kClass: KClass<T>): T {
kClass.isPrimitive() -> kClass.toDefaultPrimitiveValue()
kClass.isEnum() -> kClass.java.enumConstants.first()
kClass.isArray() -> kClass.toArrayInstance()
kClass.isClassObject() -> kClass.toClassObject()
else -> kClass.easiestConstructor().newInstance()
}
}
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -124,6 +127,11 @@ private fun <T : Any> KClass<T>.toArrayInstance(): T {
} as T
}

@Suppress("UNCHECKED_CAST")
private fun <T : Any> KClass<T>.toClassObject(): T {
return Class.forName("java.lang.Object") as T
}

private fun <T : Any> KFunction<T>.newInstance(): T {
isAccessible = true
return callBy(parameters.associate {
Expand Down
19 changes: 19 additions & 0 deletions mockito-kotlin/src/test/kotlin/CreateInstanceTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand Down Expand Up @@ -369,6 +370,24 @@ class CreateInstanceTest {
expect(result).toNotBeNull()
}

@Test
fun classObject() {
/* When */
val result = createInstance<Class<String>>()

/* Then */
expect(result).toNotBeNull()
}

@Test
fun kClassObject() {
/* When */
val result = createInstance<KClass<String>>()

/* Then */
expect(result).toNotBeNull()
}

@Test
fun uuid() {
/**
Expand Down

0 comments on commit 129f9e6

Please sign in to comment.