File tree Expand file tree Collapse file tree 3 files changed +40
-5
lines changed
main/kotlin/com/nhaarman/mockito_kotlin Expand file tree Collapse file tree 3 files changed +40
-5
lines changed Original file line number Diff line number Diff line change @@ -94,7 +94,7 @@ inline fun <reified T : Any> mock(stubbing: KStubbing<T>.(T) -> Unit): T {
9494class KStubbing <out T >(private val mock : T ) {
9595 fun <R > on (methodCall : R ) = Mockito .`when `(methodCall)
9696
97- fun <R : Any > on (methodCall : T .() -> R , c : KClass <R >): OngoingStubbing <R > {
97+ fun <R : Any > onGeneric (methodCall : T .() -> R , c : KClass <R >): OngoingStubbing <R > {
9898 val r = try {
9999 mock.methodCall()
100100 } catch (e: NullPointerException ) {
@@ -108,8 +108,16 @@ class KStubbing<out T>(private val mock: T) {
108108 return Mockito .`when `(r)
109109 }
110110
111- inline fun <reified R : Any > on (noinline methodCall : T .() -> R ): OngoingStubbing <R > {
112- return on(methodCall, R ::class )
111+ inline fun <reified R : Any > onGeneric (noinline methodCall : T .() -> R ): OngoingStubbing <R > {
112+ return onGeneric(methodCall, R ::class )
113+ }
114+
115+ fun <R > on (methodCall : T .() -> R ): OngoingStubbing <R > {
116+ return try {
117+ Mockito .`when `(mock.methodCall())
118+ } catch (e: NullPointerException ) {
119+ throw MockitoKotlinException (" NullPointerException thrown when stubbing. If you are trying to stub a generic method, try `onGeneric` instead." , e)
120+ }
113121 }
114122}
115123
Original file line number Diff line number Diff line change @@ -54,6 +54,7 @@ interface Methods {
5454 fun nullableString (s : String? )
5555
5656 fun stringResult (): String
57+ fun nullableStringResult (): String?
5758 fun builderMethod (): Methods
5859}
5960
Original file line number Diff line number Diff line change @@ -351,6 +351,20 @@ class MockitoTest {
351351 expect(result).toBeTheSameAs(mock)
352352 }
353353
354+ @Test
355+ fun testMockStubbing_nullable () {
356+ /* Given */
357+ val mock = mock<Methods > {
358+ on { nullableStringResult() } doReturn " Test"
359+ }
360+
361+ /* When */
362+ val result = mock.nullableStringResult()
363+
364+ /* Then */
365+ expect(result).toBe(" Test" )
366+ }
367+
354368 @Test
355369 fun testMockStubbing_doThrow () {
356370 /* Given */
@@ -438,10 +452,22 @@ class MockitoTest {
438452 }
439453
440454 @Test
441- fun doReturn_withGenericIntReturnType () {
455+ fun doReturn_withGenericIntReturnType_on () {
456+ /* Expect */
457+ expectErrorWithMessage(" onGeneric" ) on {
458+
459+ /* When */
460+ mock<GenericMethods <Int >> {
461+ on { genericMethod() } doReturn 2
462+ }
463+ }
464+ }
465+
466+ @Test
467+ fun doReturn_withGenericIntReturnType_onGeneric () {
442468 /* Given */
443469 val mock = mock<GenericMethods <Int >> {
444- on { genericMethod() } doReturn 2
470+ onGeneric { genericMethod() } doReturn 2
445471 }
446472
447473 /* Then */
You can’t perform that action at this time.
0 commit comments