Skip to content

Commit

Permalink
Manually provide values for primitive types
Browse files Browse the repository at this point in the history
On the JVM, primitive types get unboxed automatically,
leading to NPE's when the null quirk is used.
  • Loading branch information
nhaarman committed Jul 5, 2019
1 parent 5c51a89 commit 0ead130
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 1 deletion.
Expand Up @@ -29,7 +29,17 @@ import kotlin.reflect.KClass
import java.lang.reflect.Array as JavaArray

inline fun <reified T : Any> createInstance(): T {
return createInstance(T::class)
return when {
T::class == Boolean::class -> false as T
T::class == Byte::class -> 0.toByte() as T
T::class == Char::class -> 0.toChar() as T
T::class == Short::class -> 0.toShort() as T
T::class == Int::class -> 0 as T
T::class == Long::class -> 0L as T
T::class == Float::class -> 0f as T
T::class == Double::class -> 0.0 as T
else -> createInstance(T::class)
}
}

fun <T : Any> createInstance(kClass: KClass<T>): T {
Expand Down
7 changes: 7 additions & 0 deletions tests/src/test/kotlin/test/Classes.kt
Expand Up @@ -53,7 +53,14 @@ interface Methods {
fun closedStringMap(m: Map<Closed, String>)
fun closedSet(s: Set<Closed>)
fun string(s: String)
fun boolean(b: Boolean)
fun byte(b: Byte)
fun char(c: Char)
fun short(s: Short)
fun int(i: Int)
fun long(l: Long)
fun float(f: Float)
fun double(d: Double)
fun closedVararg(vararg c: Closed)
fun throwableClass(t: ThrowableClass)
fun nullableString(s: String?)
Expand Down
71 changes: 71 additions & 0 deletions tests/src/test/kotlin/test/MatchersTest.kt
Expand Up @@ -20,6 +20,14 @@ class MatchersTest : TestBase() {
}
}

@Test
fun anyInt() {
mock<Methods>().apply {
string("")
verify(this).string(any())
}
}

@Test
fun anyClosedClass() {
mock<Methods>().apply {
Expand Down Expand Up @@ -76,6 +84,69 @@ class MatchersTest : TestBase() {
}
}

@Test
fun anyNull_forPrimitiveBoolean() {
mock<Methods>().apply {
boolean(false)
verify(this).boolean(anyOrNull())
}
}
@Test
fun anyNull_forPrimitiveByte() {
mock<Methods>().apply {
byte(3)
verify(this).byte(anyOrNull())
}
}

@Test
fun anyNull_forPrimitiveChar() {
mock<Methods>().apply {
char('a')
verify(this).char(anyOrNull())
}
}

@Test
fun anyNull_forPrimitiveShort() {
mock<Methods>().apply {
short(3)
verify(this).short(anyOrNull())
}
}

@Test
fun anyNull_forPrimitiveInt() {
mock<Methods>().apply {
int(3)
verify(this).int(anyOrNull())
}
}

@Test
fun anyNull_forPrimitiveLong() {
mock<Methods>().apply {
long(3)
verify(this).long(anyOrNull())
}
}

@Test
fun anyNull_forPrimitiveFloat() {
mock<Methods>().apply {
float(3f)
verify(this).float(anyOrNull())
}
}

@Test
fun anyNull_forPrimitiveDouble() {
mock<Methods>().apply {
double(3.0)
verify(this).double(anyOrNull())
}
}

/** https://github.com/nhaarman/mockito-kotlin/issues/27 */
@Test
fun anyThrowableWithSingleThrowableConstructor() {
Expand Down

0 comments on commit 0ead130

Please sign in to comment.