File tree Expand file tree Collapse file tree 2 files changed +37
-1
lines changed
main/kotlin/com/nhaarman/mockito_kotlin Expand file tree Collapse file tree 2 files changed +37
-1
lines changed Original file line number Diff line number Diff line change @@ -54,10 +54,30 @@ fun <T : Any> createInstance(kClass: KClass<T>): T {
54
54
kClass.isPrimitive() -> kClass.toDefaultPrimitiveValue()
55
55
kClass.isEnum() -> kClass.java.enumConstants.first()
56
56
kClass.isArray() -> kClass.toArrayInstance()
57
- else -> kClass.constructors.sortedBy { it.parameters.size }.first ().newInstance()
57
+ else -> kClass.easiestConstructor ().newInstance()
58
58
}
59
59
}
60
60
61
+ /* *
62
+ * Tries to find the easiest constructor which it can instantiate.
63
+ */
64
+ private fun <T : Any > KClass<T>.easiestConstructor (): KFunction <T > {
65
+ return constructors.firstOrDefault(
66
+ {
67
+ it.parameters.filter {
68
+ it.type.toString().toLowerCase().contains(" array" )
69
+ }.isEmpty()
70
+ },
71
+ {
72
+ constructors.sortedBy { it.parameters.size }.first()
73
+ }
74
+ )
75
+ }
76
+
77
+ private fun <T > Collection<T>.firstOrDefault (predicate : (T ) -> Boolean , default : () -> T ): T {
78
+ return firstOrNull(predicate) ? : default()
79
+ }
80
+
61
81
@Suppress(" SENSELESS_COMPARISON" )
62
82
private fun KClass <* >.hasObjectInstance () = objectInstance != null
63
83
Original file line number Diff line number Diff line change 26
26
import com.nhaarman.expect.expect
27
27
import com.nhaarman.mockito_kotlin.createInstance
28
28
import org.junit.Test
29
+ import java.util.*
29
30
30
31
class CreateInstanceTest {
31
32
@@ -368,6 +369,21 @@ class CreateInstanceTest {
368
369
expect(result).toNotBeNull()
369
370
}
370
371
372
+ @Test
373
+ fun uuid () {
374
+ /* *
375
+ * The UUID class has a single-argument constructor that expects an array with some specific contents.
376
+ * We avoid these types of constructors by calling another constructor, if available.
377
+ * In this case, UUID(Long, Long).
378
+ */
379
+
380
+ /* When */
381
+ val result = createInstance<UUID >()
382
+
383
+ /* Then */
384
+ expect(result).toBeEqualTo(UUID (0 , 0 ))
385
+ }
386
+
371
387
private class PrivateClass private constructor(val data : String )
372
388
373
389
class ClosedClass
You can’t perform that action at this time.
0 commit comments