Skip to content

Commit 47424f2

Browse files
authored
Merge pull request #221 from nhaarman/Tapchicoma-improved-spy
Add dsl stubbing to spied classes.
2 parents 215b383 + 23de85c commit 47424f2

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
@@ -238,7 +238,11 @@ fun <T> reset(vararg mocks: T) = Mockito.reset(*mocks)
238238
fun <T> same(value: T): T = Mockito.same(value) ?: value
239239

240240
inline fun <reified T : Any> spy(): T = Mockito.spy(T::class.java)!!
241+
inline fun <reified T : Any> spy(stubbing: KStubbing<T>.(T) -> Unit ): T = Mockito.spy(T::class.java)
242+
.apply { KStubbing(this).stubbing(this) }!!
241243
fun <T> spy(value: T): T = Mockito.spy(value)!!
244+
inline fun <reified T> spy(value: T, stubbing: KStubbing<T>.(T) -> Unit): T = spy(value)
245+
.apply { KStubbing(this).stubbing(this) }!!
242246

243247
fun timeout(millis: Long): VerificationWithTimeout = Mockito.timeout(millis)!!
244248
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)