From 23de85c9e0f46fb22c57d6e377dc21a9910bcd3d Mon Sep 17 00:00:00 2001 From: Yahor Berdnikau Date: Sun, 2 Jul 2017 13:17:42 +0200 Subject: [PATCH] Add dsl stubbing to spied classes. Now it is possible to describe spied classes mock behaviour in dsl form as it was already possible with common mocks. Signed-off-by: Yahor Berdnikau --- .../com/nhaarman/mockitokotlin2/Mockito.kt | 4 ++++ .../src/test/kotlin/test/SpyTest.kt | 24 ++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/mockito-kotlin/src/main/kotlin/com/nhaarman/mockitokotlin2/Mockito.kt b/mockito-kotlin/src/main/kotlin/com/nhaarman/mockitokotlin2/Mockito.kt index 2b622aa0..eba1d04e 100644 --- a/mockito-kotlin/src/main/kotlin/com/nhaarman/mockitokotlin2/Mockito.kt +++ b/mockito-kotlin/src/main/kotlin/com/nhaarman/mockitokotlin2/Mockito.kt @@ -243,7 +243,11 @@ fun reset(vararg mocks: T) = Mockito.reset(*mocks) fun same(value: T): T = Mockito.same(value) ?: value inline fun spy(): T = Mockito.spy(T::class.java)!! +inline fun spy(stubbing: KStubbing.(T) -> Unit ): T = Mockito.spy(T::class.java) + .apply { KStubbing(this).stubbing(this) }!! fun spy(value: T): T = Mockito.spy(value)!! +inline fun spy(value: T, stubbing: KStubbing.(T) -> Unit): T = spy(value) + .apply { KStubbing(this).stubbing(this) }!! fun timeout(millis: Long): VerificationWithTimeout = Mockito.timeout(millis)!! fun times(numInvocations: Int): VerificationMode = Mockito.times(numInvocations)!! diff --git a/mockito-kotlin/src/test/kotlin/test/SpyTest.kt b/mockito-kotlin/src/test/kotlin/test/SpyTest.kt index 877d6e39..a8cf14ae 100644 --- a/mockito-kotlin/src/test/kotlin/test/SpyTest.kt +++ b/mockito-kotlin/src/test/kotlin/test/SpyTest.kt @@ -71,7 +71,7 @@ class SpyTest : TestBase() { fun doNothingWithSpy() { val date = spy(Date(0)) doNothing().whenever(date).time = 5L - date.time = 5L; + date.time = 5L expect(date.time).toBe(0L) } @@ -90,6 +90,28 @@ class SpyTest : TestBase() { expect(date.time).toBe(0L) } + @Test + fun doReturnWithDefaultInstanceSpyStubbing() { + val timeVal = 12L + + val dateSpy = spy { + on { time } doReturn timeVal + } + + expect(dateSpy.time).toBe(timeVal) + } + + @Test + fun doReturnWithSpyStubbing() { + val timeVal = 15L + + val dateSpy = spy(Date(0)) { + on { time } doReturn timeVal + } + + expect(dateSpy.time).toBe(timeVal) + } + private interface MyInterface private open class MyClass : MyInterface private class ClosedClass