File tree Expand file tree Collapse file tree 3 files changed +34
-2
lines changed
main/kotlin/com/nhaarman/mockito_kotlin Expand file tree Collapse file tree 3 files changed +34
-2
lines changed Original file line number Diff line number Diff line change @@ -93,7 +93,24 @@ inline fun <reified T : Any> mock(stubbing: KStubbing<T>.(T) -> Unit): T {
93
93
94
94
class KStubbing <out T >(private val mock : T ) {
95
95
fun <R > on (methodCall : R ) = Mockito .`when `(methodCall)
96
- fun <R > on (methodCall : T .() -> R ) = Mockito .`when `(mock.methodCall())
96
+
97
+ fun <R : Any > on (methodCall : T .() -> R , c : KClass <R >): OngoingStubbing <R > {
98
+ val r = try {
99
+ mock.methodCall()
100
+ } catch (e: NullPointerException ) {
101
+ // An NPE may be thrown by the Kotlin type system when the MockMethodInterceptor returns a
102
+ // null value for a non-nullable generic type.
103
+ // We catch this NPE to return a valid instance.
104
+ // The Mockito state has already been modified at this point to reflect
105
+ // the wanted changes.
106
+ createInstance(c)
107
+ }
108
+ return Mockito .`when `(r)
109
+ }
110
+
111
+ inline fun <reified R : Any > on (noinline methodCall : T .() -> R ): OngoingStubbing <R > {
112
+ return on(methodCall, R ::class )
113
+ }
97
114
}
98
115
99
116
infix fun <T > OngoingStubbing<T>.doReturn (t : T ): OngoingStubbing <T > = thenReturn(t)
Original file line number Diff line number Diff line change @@ -54,7 +54,11 @@ interface Methods {
54
54
fun nullableString (s : String? )
55
55
56
56
fun stringResult (): String
57
- fun builderMethod () : Methods
57
+ fun builderMethod (): Methods
58
+ }
59
+
60
+ interface GenericMethods <T > {
61
+ fun genericMethod (): T
58
62
}
59
63
60
64
class ThrowableClass (cause : Throwable ) : Throwable(cause)
Original file line number Diff line number Diff line change @@ -436,4 +436,15 @@ class MockitoTest {
436
436
expect(mock.stringResult()).toBe(" a" )
437
437
expect(mock.stringResult()).toBe(" b" )
438
438
}
439
+
440
+ @Test
441
+ fun doReturn_withGenericIntReturnType () {
442
+ /* Given */
443
+ val mock = mock<GenericMethods <Int >> {
444
+ on { genericMethod() } doReturn 2
445
+ }
446
+
447
+ /* Then */
448
+ expect(mock.genericMethod()).toBe(2 )
449
+ }
439
450
}
You can’t perform that action at this time.
0 commit comments