File tree Expand file tree Collapse file tree 3 files changed +17
-3
lines changed
mockito-kotlin/src/main/kotlin/org/mockito/kotlin
tests/src/test/kotlin/test Expand file tree Collapse file tree 3 files changed +17
-3
lines changed Original file line number Diff line number Diff line change @@ -28,11 +28,12 @@ package org.mockito.kotlin
2828import org.mockito.kotlin.internal.createInstance
2929import kotlinx.coroutines.runBlocking
3030import org.mockito.Mockito
31+ import org.mockito.exceptions.misusing.NotAMockException
3132import org.mockito.stubbing.OngoingStubbing
3233import 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
Original file line number Diff line number Diff 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}
Original file line number Diff line number Diff 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 */
You can’t perform that action at this time.
0 commit comments