Skip to content

Commit 6ee75f7

Browse files
authored
Merge pull request #92 from nhaarman/create-array-instance
Use the java class' name to create an array instance
2 parents cd16b04 + 0b43d0b commit 6ee75f7

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

mockito-kotlin/src/main/kotlin/com/nhaarman/mockito_kotlin/CreateInstance.kt

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import kotlin.reflect.defaultType
4141
import kotlin.reflect.jvm.isAccessible
4242
import kotlin.reflect.jvm.javaType
4343
import kotlin.reflect.jvm.jvmName
44+
import java.lang.reflect.Array as JavaArray
4445

4546
/**
4647
* A collection of functions that tries to create an instance of
@@ -51,6 +52,7 @@ import kotlin.reflect.jvm.jvmName
5152
* Checks whether the resource file to enable mocking of final classes is present.
5253
*/
5354
private var mockMakerInlineEnabled: Boolean? = null
55+
5456
private fun mockMakerInlineEnabled(jClass: Class<out Any>): Boolean {
5557
return mockMakerInlineEnabled ?:
5658
jClass.getResource("mockito-extensions/org.mockito.plugins.MockMaker")?.let {
@@ -137,7 +139,10 @@ private fun <T : Any> KClass<T>.toArrayInstance(): T {
137139
"LongArray" -> longArrayOf()
138140
"DoubleArray" -> doubleArrayOf()
139141
"FloatArray" -> floatArrayOf()
140-
else -> throw UnsupportedOperationException("Cannot create a generic array for $simpleName. Use createArrayInstance() or anyArray() instead.")
142+
else -> {
143+
val name = java.name.drop(2).dropLast(1)
144+
return JavaArray.newInstance(Class.forName(name), 0) as T
145+
}
141146
} as T
142147
}
143148

mockito-kotlin/src/test/kotlin/CreateInstanceTest.kt

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,10 +159,13 @@ class CreateInstanceTest {
159159
expect(result).toNotBeNull()
160160
}
161161

162-
@Test(expected = UnsupportedOperationException::class)
162+
@Test
163163
fun classArray_usingAny() {
164164
/* When */
165-
createInstance<Array<Open>>()
165+
val result = createInstance<Array<Open>>()
166+
167+
/* Then */
168+
expect(result).toBeInstanceOf<Array<Open>>()
166169
}
167170

168171
@Test

0 commit comments

Comments
 (0)