Skip to content

Commit 34cb898

Browse files
authored
Prevent silent mis-stubbing (#479)
Without this check, stubbing can silently be applied elsewhere. This fix can only be applied in `KStubbing` as `when` does not accept the mock itself and thus, the issue is presented.
1 parent 6d79682 commit 34cb898

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

mockito-kotlin/src/main/kotlin/org/mockito/kotlin/KStubbing.kt

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,12 @@ package org.mockito.kotlin
2828
import org.mockito.kotlin.internal.createInstance
2929
import kotlinx.coroutines.runBlocking
3030
import org.mockito.Mockito
31+
import org.mockito.exceptions.misusing.NotAMockException
3132
import org.mockito.stubbing.OngoingStubbing
3233
import kotlin.reflect.KClass
3334

3435

35-
inline fun <T> stubbing(
36+
inline fun <T : Any> stubbing(
3637
mock: T,
3738
stubbing: KStubbing<T>.(T) -> Unit
3839
) {
@@ -43,7 +44,10 @@ inline fun <T : Any> T.stub(stubbing: KStubbing<T>.(T) -> Unit): T {
4344
return apply { KStubbing(this).stubbing(this) }
4445
}
4546

46-
class KStubbing<out T>(val mock: T) {
47+
class KStubbing<out T : Any>(val mock: T) {
48+
init {
49+
if(!mockingDetails(mock).isMock) throw NotAMockException("Stubbing target is not a mock!")
50+
}
4751

4852
fun <R> on(methodCall: R): OngoingStubbing<R> = Mockito.`when`(methodCall)
4953

mockito-kotlin/src/main/kotlin/org/mockito/kotlin/Spying.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ fun <T> spy(value: T): T {
5656
* Creates a spy of the real object, allowing for immediate stubbing.
5757
* The spy calls <b>real</b> methods unless they are stubbed.
5858
*/
59-
inline fun <reified T> spy(value: T, stubbing: KStubbing<T>.(T) -> Unit): T {
59+
inline fun <reified T : Any> spy(value: T, stubbing: KStubbing<T>.(T) -> Unit): T {
6060
return spy(value)
6161
.apply { KStubbing(this).stubbing(this) }!!
6262
}

tests/src/test/kotlin/test/OngoingStubbingTest.kt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,16 @@ class OngoingStubbingTest : TestBase() {
241241
expect(mock.stringResult("B")).toBe("B")
242242
}
243243

244+
@Test
245+
fun stubbingRealObject() {
246+
val notAMock = ""
247+
248+
/* Expect */
249+
expectErrorWithMessage("is not a mock!").on {
250+
notAMock.stub { }
251+
}
252+
}
253+
244254
@Test
245255
fun stubbingTwiceWithCheckArgumentMatchers_throwsException() {
246256
/* Expect */

0 commit comments

Comments
 (0)