Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Account for Class<T> when creating instances. #28

Merged
merged 1 commit into from
Mar 27, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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