Skip to content

Commit 23de85c

Browse files
Tapchicomanhaarman
authored andcommitted
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 <egorr.berd@gmail.com>
1 parent 3bae5f1 commit 23de85c

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,11 @@ fun <T> reset(vararg mocks: T) = Mockito.reset(*mocks)
243243
fun <T> same(value: T): T = Mockito.same(value) ?: value
244244

245245
inline fun <reified T : Any> spy(): T = Mockito.spy(T::class.java)!!
246+
inline fun <reified T : Any> spy(stubbing: KStubbing<T>.(T) -> Unit ): T = Mockito.spy(T::class.java)
247+
.apply { KStubbing(this).stubbing(this) }!!
246248
fun <T> spy(value: T): T = Mockito.spy(value)!!
249+
inline fun <reified T> spy(value: T, stubbing: KStubbing<T>.(T) -> Unit): T = spy(value)
250+
.apply { KStubbing(this).stubbing(this) }!!
247251

248252
fun timeout(millis: Long): VerificationWithTimeout = Mockito.timeout(millis)!!
249253
fun times(numInvocations: Int): VerificationMode = Mockito.times(numInvocations)!!

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

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ class SpyTest : TestBase() {
7171
fun doNothingWithSpy() {
7272
val date = spy(Date(0))
7373
doNothing().whenever(date).time = 5L
74-
date.time = 5L;
74+
date.time = 5L
7575
expect(date.time).toBe(0L)
7676
}
7777

@@ -90,6 +90,28 @@ class SpyTest : TestBase() {
9090
expect(date.time).toBe(0L)
9191
}
9292

93+
@Test
94+
fun doReturnWithDefaultInstanceSpyStubbing() {
95+
val timeVal = 12L
96+
97+
val dateSpy = spy<Date> {
98+
on { time } doReturn timeVal
99+
}
100+
101+
expect(dateSpy.time).toBe(timeVal)
102+
}
103+
104+
@Test
105+
fun doReturnWithSpyStubbing() {
106+
val timeVal = 15L
107+
108+
val dateSpy = spy(Date(0)) {
109+
on { time } doReturn timeVal
110+
}
111+
112+
expect(dateSpy.time).toBe(timeVal)
113+
}
114+
93115
private interface MyInterface
94116
private open class MyClass : MyInterface
95117
private class ClosedClass

0 commit comments

Comments
 (0)