Skip to content

Commit 514eb65

Browse files
committed
Allow nullable return types for onGeneric
1 parent e0d2b0d commit 514eb65

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

mockito-kotlin/src/main/kotlin/com/nhaarman/mockitokotlin2/Mockito.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ inline fun <reified T : Any> mock(s: MockSettings): T = Mockito.mock(T::class.ja
193193
class KStubbing<out T>(private val mock: T) {
194194
fun <R> on(methodCall: R) = Mockito.`when`(methodCall)
195195

196-
fun <R : Any> onGeneric(methodCall: T.() -> R, c: KClass<R>): OngoingStubbing<R> {
196+
fun <R : Any> onGeneric(methodCall: T.() -> R?, c: KClass<R>): OngoingStubbing<R> {
197197
val r = try {
198198
mock.methodCall()
199199
} catch (e: NullPointerException) {
@@ -207,7 +207,7 @@ class KStubbing<out T>(private val mock: T) {
207207
return Mockito.`when`(r)
208208
}
209209

210-
inline fun <reified R : Any> onGeneric(noinline methodCall: T.() -> R): OngoingStubbing<R> {
210+
inline fun <reified R : Any> onGeneric(noinline methodCall: T.() -> R?): OngoingStubbing<R> {
211211
return onGeneric(methodCall, R::class)
212212
}
213213

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ abstract class ThrowingConstructor {
7777

7878
interface GenericMethods<T> {
7979
fun genericMethod(): T
80+
fun nullableReturnType(): T?
8081
}
8182

8283
class ThrowableClass(cause: Throwable) : Throwable(cause)

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1004,6 +1004,15 @@ class MockitoTest : TestBase() {
10041004
expect(mock.genericMethod()).toBe(2)
10051005
}
10061006

1007+
@Test
1008+
fun doReturn_withGenericNullableReturnType_onGeneric() {
1009+
val m = mock<GenericMethods<String>> {
1010+
onGeneric { nullableReturnType() } doReturn "Test"
1011+
}
1012+
1013+
expect(m.nullableReturnType()).toBe("Test")
1014+
}
1015+
10071016
@Test
10081017
fun isA_withNonNullableString() {
10091018
mock<Methods>().apply {

0 commit comments

Comments
 (0)