How to use OngoingStubbing class of org.mockito.kotlin package

Best Mockito-kotlin code snippet using org.mockito.kotlin.OngoingStubbing

OngoingStubbing.kt

Source:OngoingStubbing.kt Github

copy

Full Screen

...26import org.mockito.Mockito27import org.mockito.invocation.InvocationOnMock28import org.mockito.kotlin.internal.SuspendableAnswer29import org.mockito.stubbing.Answer30import org.mockito.stubbing.OngoingStubbing31import kotlin.reflect.KClass32/**33 * Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called.34 *35 * Alias for [Mockito.when].36 */37@Suppress("NOTHING_TO_INLINE")38inline fun <T> whenever(methodCall: T): OngoingStubbing<T> {39 return Mockito.`when`(methodCall)!!40}41/**42 * Sets a return value to be returned when the method is called.43 *44 * Alias for [OngoingStubbing.thenReturn].45 */46infix fun <T> OngoingStubbing<T>.doReturn(t: T): OngoingStubbing<T> {47 return thenReturn(t)48}49/**50 * Sets consecutive return values to be returned when the method is called.51 *52 * Alias for [OngoingStubbing.thenReturn].53 */54fun <T> OngoingStubbing<T>.doReturn(t: T, vararg ts: T): OngoingStubbing<T> {55 return thenReturn(t, *ts)56}57/**58 * Sets consecutive return values to be returned when the method is called.59 */60inline infix fun <reified T> OngoingStubbing<T>.doReturnConsecutively(ts: List<T>): OngoingStubbing<T> {61 return thenReturn(62 ts[0],63 *ts.drop(1).toTypedArray()64 )65}66/**67 * Sets Throwable objects to be thrown when the method is called.68 *69 * Alias for [OngoingStubbing.thenThrow].70 */71infix fun <T> OngoingStubbing<T>.doThrow(t: Throwable): OngoingStubbing<T> {72 return thenThrow(t)73}74/**75 * Sets Throwable objects to be thrown when the method is called.76 *77 * Alias for [OngoingStubbing.doThrow].78 */79fun <T> OngoingStubbing<T>.doThrow(80 t: Throwable,81 vararg ts: Throwable82): OngoingStubbing<T> {83 return thenThrow(t, *ts)84}85/**86 * Sets a Throwable type to be thrown when the method is called.87 */88infix fun <T> OngoingStubbing<T>.doThrow(t: KClass<out Throwable>): OngoingStubbing<T> {89 return thenThrow(t.java)90}91/**92 * Sets Throwable classes to be thrown when the method is called.93 */94fun <T> OngoingStubbing<T>.doThrow(95 t: KClass<out Throwable>,96 vararg ts: KClass<out Throwable>97): OngoingStubbing<T> {98 return thenThrow(t.java, *ts.map { it.java }.toTypedArray())99}100/**101 * Sets a generic Answer for the method.102 *103 * Alias for [OngoingStubbing.thenAnswer].104 */105infix fun <T> OngoingStubbing<T>.doAnswer(answer: Answer<*>): OngoingStubbing<T> {106 return thenAnswer(answer)107}108/**109 * Sets a generic Answer for the method using a lambda.110 */111infix fun <T> OngoingStubbing<T>.doAnswer(answer: (InvocationOnMock) -> T?): OngoingStubbing<T> {112 return thenAnswer(answer)113}114infix fun <T> OngoingStubbing<T>.doSuspendableAnswer(answer: suspend (InvocationOnMock) -> T?): OngoingStubbing<T> {115 return thenAnswer(SuspendableAnswer(answer))116}...

Full Screen

Full Screen

ThenAction.kt

Source:ThenAction.kt Github

copy

Full Screen

...16 */17package net.paslavsky.kotlin.mockito18import org.mockito.Mockito19import org.mockito.invocation.InvocationOnMock20import org.mockito.stubbing.OngoingStubbing21import kotlin.reflect.KClass22/**23 * Stubber for Mockito Kt24 *25 * @author [Andrey Paslavsky](mailto:a.paslavsky@gmail.com)26 * @since 0.0.127 */28@Suppress("unused")29class ThenAction<T, M : Any>(30 private val mock: M,31 private val call: M.() -> T,32 private val chains: MutableSet<ThenAction<*,*>.ActionChain<*>>33) {34 private val dummy: Dummy = Mockito.mock(Dummy::class.java)35 private open class Dummy {36 open fun doSomething(): Any? = null37 }38 fun thenThrow(toBeThrown: KClass<out Throwable>) = ActionChain<T>({ thenThrow(toBeThrown.java) })39 fun thenThrow(toBeThrown: Throwable) = ActionChain<T>({ thenThrow(toBeThrown) })40 fun thenCallRealMethod() = ActionChain<T>({ thenCallRealMethod() })41 fun thenAnswer(answer: (invocation: InvocationOnMock) -> T) = ActionChain<T>({ thenAnswer(answer) })42 fun thenNothing() = ActionChain<T>({ then {} })43 fun thenReturn(toBeReturned: T?) = ActionChain<T>({ thenReturn(toBeReturned) })44 inner class ActionChain<T>(private var action: OngoingStubbing<T>.() -> OngoingStubbing<T>) {45 init {46 chains.add(this)47 }48 fun thenThrow(toBeThrown: KClass<out Throwable>) = addAction { thenThrow(toBeThrown.java) }49 fun thenThrow(toBeThrown: Throwable) = addAction { thenThrow(toBeThrown) }50 fun thenCallRealMethod() = addAction { thenCallRealMethod() }51 fun thenAnswer(answer: (invocation: InvocationOnMock) -> T) = addAction { thenAnswer(answer) }52 fun thenNothing() = addAction { then {} }53 fun thenReturn(toBeReturned: T?) = addAction { thenReturn(toBeReturned) }54 private fun addAction(newAction: OngoingStubbing<T>.() -> OngoingStubbing<T>): ActionChain<T> {55 val previous = action56 action = { previous().newAction() }57 return this58 }59 internal fun done() {60 try {61 val call1 = mock.call()62 @Suppress("UNCHECKED_CAST")63 val stubbing = Mockito.`when`(call1) as OngoingStubbing<T>64 stubbing.action()65 } catch(e: Exception) {66 resetMockitoStubbingState()67 throw e68 }69 }70 private fun resetMockitoStubbingState() {71 try {72 Mockito.doReturn(Any()).`when`(dummy).doSomething()73 } catch (ignore: Exception) {74 } finally {75 Mockito.reset(dummy)76 }77 }...

Full Screen

Full Screen

KStubbing.kt

Source:KStubbing.kt Github

copy

Full Screen

...25package org.mockito.kotlin26import org.mockito.kotlin.internal.createInstance27import kotlinx.coroutines.runBlocking28import org.mockito.Mockito29import org.mockito.stubbing.OngoingStubbing30import kotlin.reflect.KClass31inline fun <T> stubbing(32 mock: T,33 stubbing: KStubbing<T>.(T) -> Unit34) {35 KStubbing(mock).stubbing(mock)36}37inline fun <T : Any> T.stub(stubbing: KStubbing<T>.(T) -> Unit): T {38 return apply { KStubbing(this).stubbing(this) }39}40class KStubbing<out T>(val mock: T) {41 fun <R> on(methodCall: R): OngoingStubbing<R> = Mockito.`when`(methodCall)42 fun <R : Any> onGeneric(methodCall: T.() -> R?, c: KClass<R>): OngoingStubbing<R> {43 val r = try {44 mock.methodCall()45 } catch (e: NullPointerException) {46 // An NPE may be thrown by the Kotlin type system when the MockMethodInterceptor returns a47 // null value for a non-nullable generic type.48 // We catch this NPE to return a valid instance.49 // The Mockito state has already been modified at this point to reflect50 // the wanted changes.51 createInstance(c)52 }53 return Mockito.`when`(r)54 }55 inline fun <reified R : Any> onGeneric(noinline methodCall: T.() -> R?): OngoingStubbing<R> {56 return onGeneric(methodCall, R::class)57 }58 fun <R> on(methodCall: T.() -> R): OngoingStubbing<R> {59 return try {60 Mockito.`when`(mock.methodCall())61 } catch (e: NullPointerException) {62 throw MockitoKotlinException(63 "NullPointerException thrown when stubbing.\nThis may be due to two reasons:\n\t- The method you're trying to stub threw an NPE: look at the stack trace below;\n\t- You're trying to stub a generic method: try `onGeneric` instead.",64 e65 )66 }67 }68 fun <T : Any, R> KStubbing<T>.onBlocking(69 m: suspend T.() -> R70 ): OngoingStubbing<R> {71 return runBlocking { Mockito.`when`(mock.m()) }72 }73}

Full Screen

Full Screen

KMockito.kt

Source:KMockito.kt Github

copy

Full Screen

2import com.oliver_curtis.movies_list.helper.matchers.KArgumentMatcher3import com.oliver_curtis.movies_list.helper.matchers.KAny4import kotlinx.coroutines.runBlocking5import org.mockito.Mockito6import org.mockito.stubbing.OngoingStubbing7import org.mockito.verification.VerificationMode8/**9 * Kotlin-friendly Mockito functions.10 */11class KMockito {12 companion object {13 /**14 * Kotlin-friendly "any" matcher. This matcher will always return a non-null reference that15 * keeps the Kotlin runtime happy.16 *17 * @param dummyInstance a dummy instance used to always return a non-null reference. This18 * instance is never going to be used in any tests so its value does not matter.19 *20 * @return a Kotlin-friendly matcher that matches any argument value and will never return21 * a non-null reference22 */23 fun <T> any(dummyInstance: T) = argThat(KAny(dummyInstance))24 /**25 * Kotlin-friendly matcher. This matcher will always return a non-null reference that26 * keeps the Kotlin runtime happy.27 *28 * @param matcher the matcher that will actually perform the desired argument matching29 *30 * @return a Kotlin-friendly matcher that matches any argument value and will never return31 * a non-null reference32 *33 * @see KArgumentMatcher34 */35 fun <T> argThat(matcher: KArgumentMatcher<T>): T {36 return Mockito.argThat(matcher) ?: matcher.dummyInstance()37 }38 /**39 * Mockito.when function for suspended method calls.40 */41 fun <T> suspendedWhen(methodCall: suspend () -> T): OngoingStubbing<T> {42 return Mockito.`when`(runBlocking { methodCall.invoke() })43 }44 /**45 * Mockito.verify function for suspended method calls.46 */47 fun <T> suspendedVerify(mock: T, method: suspend T.() -> Unit) {48 runBlocking { Mockito.verify(mock).method() }49 }50 /**51 * Mockito.verify function, with verification mode, for suspended method calls.52 */53 fun <T> suspendedVerify(mock: T, mode: VerificationMode, method: suspend T.() -> Unit) {54 runBlocking { Mockito.verify(mock, mode).method() }55 }...

Full Screen

Full Screen

MockitoKotlinHelpers.kt

Source:MockitoKotlinHelpers.kt Github

copy

Full Screen

...3 * Helper functions that are workarounds to kotlin Runtime Exceptions when using kotlin.4 */5import org.mockito.ArgumentCaptor6import org.mockito.Mockito7import org.mockito.stubbing.OngoingStubbing8/**9 * Returns Mockito.eq() as nullable type to avoid java.lang.IllegalStateException when10 * null is returned.11 *12 * Generic T is nullable because implicitly bounded by Any?.13 */14fun <T> eq(obj: T): T = Mockito.eq<T>(obj)15/**16 * Returns Mockito.any() as nullable type to avoid java.lang.IllegalStateException when17 * null is returned.18 */19fun <T> any(): T = Mockito.any<T>()20/**21 * Returns ArgumentCaptor.capture() as nullable type to avoid java.lang.IllegalStateException22 * when null is returned.23 */24fun <T> capture(argumentCaptor: ArgumentCaptor<T>): T = argumentCaptor.capture()25fun <T> ArgumentCaptor<T>.captureForKotlin() = androidx.paging.capture(this)26/**27 * Helper function for creating an argumentCaptor in kotlin.28 */29inline fun <reified T : Any> argumentCaptor(): ArgumentCaptor<T> =30 ArgumentCaptor.forClass(T::class.java)31// To avoid having to use backticks for "when"32fun <T> whenever(methodCall: T): OngoingStubbing<T> =33 Mockito.`when`(methodCall)...

Full Screen

Full Screen

TestUtil.kt

Source:TestUtil.kt Github

copy

Full Screen

1package com.radutopor.dogsshouldvote2import org.mockito.internal.invocation.InterceptedInvocation3import org.mockito.invocation.InvocationOnMock4import org.mockito.stubbing.OngoingStubbing5import kotlin.coroutines.Continuation6import kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn7/**8 * This should be replaced after the release of https://github.com/nhaarman/mockito-kotlin/pull/3579 */10@Suppress("UNCHECKED_CAST")11infix fun <T> OngoingStubbing<T>.willAnswer(answer: suspend (InvocationOnMock) -> T?): OngoingStubbing<T> {12 return thenAnswer {13 //all suspend functions/lambdas has Continuation as the last argument.14 //InvocationOnMock does not see last argument15 val rawInvocation = it as InterceptedInvocation16 val continuation = rawInvocation.rawArguments.last() as Continuation<T?>17 answer.startCoroutineUninterceptedOrReturn(it, continuation)18 }19}...

Full Screen

Full Screen

TestUtils.kt

Source:TestUtils.kt Github

copy

Full Screen

1import org.mockito.Mockito2import org.mockito.invocation.InvocationOnMock3import org.mockito.stubbing.OngoingStubbing4import kotlin.reflect.KClass5internal fun <T : Any> mock(clazz: KClass<T>): T = Mockito.mock(clazz.java)6internal fun <T> callOf(methodCall: T): OngoingStubbing<T> = Mockito.`when`(methodCall)7internal infix fun <T> OngoingStubbing<T>.willReturn(value: T): OngoingStubbing<T> = thenReturn(value)8internal infix fun <T> OngoingStubbing<T>.willDo(f: (InvocationOnMock) -> T): OngoingStubbing<T> = then(f)...

Full Screen

Full Screen

MockitoExtensions.kt

Source:MockitoExtensions.kt Github

copy

Full Screen

1package com.ninja_squad.dbsetup_kotlin2import org.mockito.Mockito3import org.mockito.stubbing.OngoingStubbing4/**5 * @author JB Nizet6 */7fun <T> whenever(methodCall: T): OngoingStubbing<T> = Mockito.`when`(methodCall)8inline fun <reified T: Any> mock(): T = Mockito.mock(T::class.java)...

Full Screen

Full Screen

OngoingStubbing

Using AI Code Generation

copy

Full Screen

1 val mockedList = mock<MutableList<String>>()2 whenever(mockedList[0]).thenReturn("first")3 println(mockedList[0])4 whenever(mockedList[0]).thenReturn("second")5 println(mockedList[0])6 println(mockedList[0])7 whenever(mockedList[0]) doReturn "third"8 println(mockedList[0])9 whenever(mockedList[0]) doReturn "fourth"10 println(mockedList[0])11 println(mockedList[999])12 verify(mockedList).get(0)13}14fun verifyMethodCall() {15 val mockedList = mock<MutableList<String>>()16 mockedList.add("one")17 mockedList.clear()18 verify(mockedList).add("one")19 verify(mockedList).clear()20}21fun verifyMethodCallWithArgumentMatchers() {22 val mockedList = mock<MutableList<String>>()23 mockedList.add("one")24 mockedList.clear()25 verify(mockedList).add(argThat { startsWith("o") })26 verify(mockedList).clear()27}28fun verifyMethodCallWithArgumentMatchers2() {29 val mockedList = mock<MutableList<String>>()30 mockedList.add("one")31 mockedList.clear()32 verify(mockedList).add(argThat { startsWith("o") })33 verify(mockedList).clear()34}

Full Screen

Full Screen

OngoingStubbing

Using AI Code Generation

copy

Full Screen

1val mockList = mock < List < Int >>() mockList . get ( 0 ) . thenReturn ( 42 )2val mockList = mock < List < Int >>() mockList . get ( 0 ) . thenReturn ( 42 )3val mockList = mock < List < Int >>() mockList . get ( 0 ) . thenReturn ( 42 )4val mockList = mock < List < Int >>() mockList . get ( 0 ) . thenReturn ( 42 )5val mockList = mock < List < Int >>() mockList . get ( 0 ) . thenReturn ( 42 )6val mockList = mock < List < Int >>() mockList . get ( 0 ) . thenReturn ( 42 )7val mockList = mock < List < Int >>() mockList . get ( 0 ) . thenReturn ( 42 )8val mockList = mock < List < Int >>() mockList . get ( 0 ) . thenReturn ( 42 )9val mockList = mock < List < Int >>() mockList . get ( 0 ) . thenReturn ( 42 )10val mockList = mock < List < Int >>() mockList . get ( 0 ) . thenReturn ( 42 )11val mockList = mock < List < Int >>() mockList . get ( 0 ) . thenReturn ( 42 )12val mockList = mock < List < Int >>() mockList . get ( 0 ) . thenReturn ( 42 )13val mockList = mock < List < Int >>() mock

Full Screen

Full Screen

OngoingStubbing

Using AI Code Generation

copy

Full Screen

1Every { mock.someMethod() } returns 1 returns 22Every { mock.someMethod() } returnsMany listOf(1, 2)3Every { mock.someMethod() } returnsMany listOf(1, 2) returnsMany listOf(3, 4)4Every { mock.someMethod() } returns 1 returns 25Every { mock.someMethod() } returnsMany listOf(1, 2)6Every { mock.someMethod() } returnsMany listOf(1, 2) returnsMany listOf(3, 4)7Every { mock.someMethod() } returns 1 returns 28Every { mock.someMethod() } returnsMany listOf(1, 2)9Every { mock.someMethod() } returnsMany listOf(1, 2) returnsMany listOf(3, 4)10Every { mock.someMethod() } returns 1 returns 211Every { mock.someMethod() } returnsMany listOf(1, 2)12Every { mock.someMethod() } returnsMany listOf(1, 2) returnsMany listOf(3, 4)13Every { mock.someMethod() } returns 1 returns 214Every { mock.someMethod() } returnsMany listOf(1, 2)15Every { mock.someMethod() } returnsMany listOf(1, 2) returnsMany listOf(3, 4)16Every { mock.someMethod() } returns 1 returns 217Every { mock.someMethod() } returnsMany listOf(1, 2)18Every { mock.someMethod() } returnsMany listOf(1, 2) returnsMany listOf(3, 4)19Every { mock.someMethod() } returns

Full Screen

Full Screen

OngoingStubbing

Using AI Code Generation

copy

Full Screen

1 whenever(mockedList.get(0)).thenThrow(IllegalArgumentException())2 doReturn(2).whenever(mockedList).size3 }4I have a question regarding the `whenever()` function. What is the difference between the following two lines of code?5 whenever(mockedList.get(0)).thenThrow(IllegalArgumentException())6 whenever(mockedList[0]).thenThrow(IllegalArgumentException())7P.P.P.P.P.S. I have already asked the same question on the Mockito Slack (I am using the same account as here): [mockito.slack.com/archives/C0C7N8WJ8/p1603168752000600](mockito.slack.com/archives/C0C7...)

Full Screen

Full Screen

OngoingStubbing

Using AI Code Generation

copy

Full Screen

1val mock = mock<Collection<String>>()2stubbing.thenThrow(UnsupportedOperationException::class.java)3stubbing.thenReturn(1)4stubbing.thenReturn(2,3)5stubbing.then { it > 2 }6val mock = mock<Collection<String>>()7stubbing.thenThrow(UnsupportedOperationException::class.java)8stubbing.thenReturn(1)9stubbing.thenReturn(2,3)10stubbing.then { it > 2 }

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mockito-kotlin automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in OngoingStubbing

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful