diff --git a/mockito-kotlin/src/main/kotlin/com/nhaarman/mockito_kotlin/Mockito.kt b/mockito-kotlin/src/main/kotlin/com/nhaarman/mockito_kotlin/Mockito.kt index 7b520fe6..a35ce024 100644 --- a/mockito-kotlin/src/main/kotlin/com/nhaarman/mockito_kotlin/Mockito.kt +++ b/mockito-kotlin/src/main/kotlin/com/nhaarman/mockito_kotlin/Mockito.kt @@ -41,12 +41,16 @@ fun after(millis: Long) = Mockito.after(millis) /** Matches any object, excluding nulls. */ inline fun any() = Mockito.any(T::class.java) ?: createInstance() + /** Matches anything, including nulls. */ inline fun anyOrNull(): T = Mockito.any() ?: createInstance() + /** Matches any vararg object, including nulls. */ inline fun anyVararg(): T = Mockito.any() ?: createInstance() + /** Matches any array of type T. */ inline fun anyArray(): Array = Mockito.any(Array::class.java) ?: arrayOf() + inline fun argThat(noinline predicate: T.() -> Boolean) = Mockito.argThat { it -> (it as T).predicate() } ?: createInstance(T::class) inline fun argForWhich(noinline predicate: T.() -> Boolean) = argThat(predicate) @@ -80,8 +84,11 @@ inline fun mock(defaultAnswer: Answer): T = Mockito.mock( inline fun mock(s: MockSettings): T = Mockito.mock(T::class.java, s)!! inline fun mock(s: String): T = Mockito.mock(T::class.java, s)!! -inline fun mock(stubbing: KStubbing.() -> Unit): T - = Mockito.mock(T::class.java)!!.apply { stubbing(KStubbing(this)) } +inline fun mock(stubbing: KStubbing.(T) -> Unit): T { + return mock().apply { + KStubbing(this).stubbing(this) + } +} class KStubbing(private val mock: T) { fun on(methodCall: R) = Mockito.`when`(methodCall) diff --git a/mockito-kotlin/src/test/kotlin/Classes.kt b/mockito-kotlin/src/test/kotlin/Classes.kt index 9107ebc3..979c71b2 100644 --- a/mockito-kotlin/src/test/kotlin/Classes.kt +++ b/mockito-kotlin/src/test/kotlin/Classes.kt @@ -54,6 +54,7 @@ interface Methods { fun nullableString(s: String?) fun stringResult(): String + fun builderMethod() : Methods } class ThrowableClass(cause: Throwable) : Throwable(cause) diff --git a/mockito-kotlin/src/test/kotlin/MockitoTest.kt b/mockito-kotlin/src/test/kotlin/MockitoTest.kt index 9d3a5fa4..c40f9525 100644 --- a/mockito-kotlin/src/test/kotlin/MockitoTest.kt +++ b/mockito-kotlin/src/test/kotlin/MockitoTest.kt @@ -361,6 +361,20 @@ class MockitoTest { expect(result).toBe("A") } + @Test + fun testMockStubbing_builder() { + /* Given */ + val mock = mock { mock -> + on { builderMethod() } doReturn mock + } + + /* When */ + val result = mock.builderMethod() + + /* Then */ + expect(result).toBeTheSameAs(mock) + } + @Test fun doReturn_withSingleItemList() { /* Given */