Best Mockito-kotlin code snippet using org.mockito.kotlin.OngoingStubbing.OngoingStubbing.doReturn
MockScenario.kt
Source:MockScenario.kt
1package me.hufman.androidautoidrive2import android.content.Context3import androidx.databinding.ObservableArrayList4import androidx.lifecycle.LiveData5import androidx.lifecycle.MutableLiveData6import com.nhaarman.mockito_kotlin.doAnswer7import com.nhaarman.mockito_kotlin.doReturn8import com.nhaarman.mockito_kotlin.mock9import me.hufman.androidautoidrive.calendar.CalendarEvent10import me.hufman.androidautoidrive.calendar.PhoneCalendar11import me.hufman.androidautoidrive.carapp.music.MusicAppMode12import me.hufman.androidautoidrive.connections.CarConnectionDebugging13import me.hufman.androidautoidrive.music.MusicAppDiscovery14import me.hufman.androidautoidrive.music.MusicAppInfo15import me.hufman.androidautoidrive.music.MusicSessions16import me.hufman.androidautoidrive.phoneui.MusicAppDiscoveryThread17import me.hufman.androidautoidrive.phoneui.viewmodels.*18import org.mockito.Mockito19import org.mockito.stubbing.Answer20import org.mockito.stubbing.OngoingStubbing21import java.util.*22import kotlin.collections.ArrayList23// Helpers for mocking LiveData/Context values24infix fun <T> OngoingStubbing<LiveData<T>>.doReturn(value: T): OngoingStubbing<LiveData<T>> = thenReturn(MutableLiveData(value))25infix fun OngoingStubbing<BooleanLiveSetting>.doReturn(value: Boolean): OngoingStubbing<BooleanLiveSetting> = thenAnswer{ mock<BooleanLiveSetting> { on {getValue()} doReturn value } }26infix fun OngoingStubbing<StringLiveSetting>.doReturn(value: String): OngoingStubbing<StringLiveSetting> = thenAnswer{ mock<StringLiveSetting> { on {getValue()} doReturn value } }27infix fun <T> OngoingStubbing<LiveData<Context.() -> T>>.doReturnContexted(value: Context.() -> T): OngoingStubbing<LiveData<Context.() -> T>> = thenReturn(MutableLiveData(value))28infix fun <T> OngoingStubbing<MutableLiveData<Context.() -> T>>.doReturnMutableContexted(value: Context.() -> T): OngoingStubbing<MutableLiveData<Context.() -> T>> = thenReturn(MutableLiveData(value))29class MockScenario(context: Context) {30 val connectionDebugging = mock<CarConnectionDebugging> {31 on {isBMWConnectedInstalled} doReturn false32 on {isBMWMineInstalled} doReturn true33 on {isBMWInstalled} doReturn true34 on {isConnectedSecurityInstalled} doReturn true35 on {isConnectedSecurityConnected} doReturn true36 on {isBCLConnected} doReturn true37 on {isBTConnected} doReturn true38 on {isSPPAvailable} doReturn true39 on {isA2dpConnected} doReturn true40 on {carBrand} doReturn "BMW"41 }42 val carInfo = mock<CarInformation> {43 on {capabilities} doReturn mapOf(44 "hmi.type" to "BMW ID5",45 "hmi.version" to "NBTevo_ID5_1903",46 "navi" to "true",47 "tts" to "true",48 "vehicle.type" to "F22"49 )50 }51 val musicAppMode = mock<MusicAppMode> {52 on {heuristicAudioContext()} doReturn true53 on {shouldId5Playback()} doReturn true54 }55 val carCapabilitiesViewModel = CarCapabilitiesViewModel(carInfo, musicAppMode)56 val connectionStatusModel = ConnectionStatusModel(connectionDebugging, carInfo)57 val dependencyInfoModel = DependencyInfoModel(connectionDebugging, mock())58 val connectionTipsModel = ConnectionTipsModel(connectionDebugging)59 val capabilitiesTipsModel = CapabilitiesTipsModel(carInfo)60 val calendarSettingsModel = mock<CalendarSettingsModel> {61 on {calendarEnabled} doReturn true62 on {areCalendarsFound} doReturn true63 on {autonav} doReturn true64 }65 val calendarEventsModel = mock<CalendarEventsModel> {66 on {calendars} doReturn ArrayList(listOf(67 PhoneCalendar("Holidays", false, 0xcff9eb),68 PhoneCalendar("Personal", true, 0xdbe6fd),69 ))70 on {upcomingEvents} doReturn ArrayList(listOf(71 CalendarEvent("Dinner", Calendar.getInstance().also {72 it[Calendar.MONTH] = 273 it[Calendar.DAY_OF_MONTH] = 1974 it[Calendar.HOUR_OF_DAY] = 1875 it[Calendar.MINUTE] = 076 }, Calendar.getInstance().also {77 it[Calendar.MONTH] = 278 it[Calendar.DAY_OF_MONTH] = 1979 it[Calendar.HOUR_OF_DAY] = 2080 it[Calendar.MINUTE] = 081 }, "", "", 0xdbe6fd)82 ))83 }84 val musicApps = ObservableArrayList<MusicAppInfo>().apply {85 add(MusicAppInfo("Green Player", context.getDrawable(R.drawable.ic_test_music_app2)!!, "mock", null).apply {86 connectable = true87 browseable = true88 searchable = true89 })90 add(MusicAppInfo("Music Player", context.getDrawable(R.drawable.ic_test_music_app1)!!, "mock", null).apply {91 controllable = true92 })93 add(MusicAppInfo("Unsupported Player", context.getDrawable(R.drawable.ic_test_music_app1)!!, "mock", null).apply {94 connectable = false95 hidden = true96 })97 }98 val musicAppDiscovery = mock<MusicAppDiscovery> {99 on {musicSessions} doReturn mock<MusicSessions>()100 }101 val musicAppDiscoveryThread = mock<MusicAppDiscoveryThread> {102 on {discovery} doReturn musicAppDiscovery103 }104 val musicAppsModel = mock<MusicAppsViewModel> {105 on {validApps} doReturn ObservableArrayList<MusicAppInfo>().apply {addAll(musicApps.filter { it.connectable || it.controllable})}106 on {allApps} doReturn musicApps107 on {musicAppDiscoveryThread} doReturn musicAppDiscoveryThread108 }109 val permissionsModel = mock<PermissionsModel> {110 on {hasSpotify} doReturn true111 on {hasSpotifyControlPermission} doReturn true112 on {isSpotifyWebApiAuthorized} doReturn true113 on {hasCalendarPermission} doReturn true114 on {hasNotificationPermission} doReturn true115 on {hasSmsPermission} doReturn true116 on {hasLocationPermission} doReturn true117 on {hasBackgroundPermission} doReturn true118 }119 // https://stackoverflow.com/a/60119030/169035120 val nonNullStringAnswer = Answer { invocation ->121 // println("Returning default answer for $invocation with type ${invocation.method.returnType}")122 when (invocation.method.returnType) {123 String::class.java -> ""124 StringLiveSetting::class.java -> mock<StringLiveSetting> { on { value } doReturn "" }125 else -> Mockito.RETURNS_DEFAULTS.answer(invocation)126 }127 }128 val mapSettingsModel = mock<MapSettingsModel>(defaultAnswer=nonNullStringAnswer) {129 on {mapEnabled} doReturn true130 on {mapPhoneGps} doReturn false131 on {mapWidescreen} doReturn true132 }133 val navigationStatusModel = mock<NavigationStatusModel> {134 on {isConnected} doReturn true135 on {query} doAnswer {MutableLiveData("")}136 on {carNavigationStatus} doReturnContexted {getString(R.string.lbl_navigationstatus_inactive)}137 on {searchStatus} doReturnMutableContexted {getString(R.string.lbl_navigation_listener_pending)}138 on {searchFailed} doAnswer {MutableLiveData(false)}139 }140 val notificationSettingsModel = mock<NotificationSettingsModel> {141 on {notificationEnabled} doReturn true142 on {notificationPopup} doReturn false143 on {notificationPopupPassenger} doReturn false144 on {notificationReadout} doReturn false145 on {notificationReadoutPopupPassenger} doReturn false146 on {notificationSound} doReturn false147 }148 val languageSettingsModel = mock<LanguageSettingsModel> {149 on { lblPreferCarLanguage } doReturnContexted { getString(R.string.lbl_language_prefercar) }150 on { showAdvanced } doReturn true151 on { preferCarLanguage } doReturn true152 on { forceCarLanguage} doReturn ""153 }154 val viewModels = MockViewModels().also {155 it[CarCapabilitiesViewModel::class.java] = carCapabilitiesViewModel156 it[CalendarSettingsModel::class.java] = calendarSettingsModel157 it[CalendarEventsModel::class.java] = calendarEventsModel158 it[ConnectionStatusModel::class.java] = connectionStatusModel159 it[DependencyInfoModel::class.java] = dependencyInfoModel160 it[LanguageSettingsModel::class.java] = languageSettingsModel161 it[MapSettingsModel::class.java] = mapSettingsModel162 it[MusicAppsViewModel::class.java] = musicAppsModel163 it[NavigationStatusModel::class.java] = navigationStatusModel164 it[NotificationSettingsModel::class.java] = notificationSettingsModel165 it[PermissionsModel::class.java] = permissionsModel166 it[TipsModel::class.java] = connectionTipsModel // set the initial TipsModel for the main tab167 }168}...
Mocklin.kt
Source:Mocklin.kt
1package mocklin2import org.mockito.InOrder3import org.mockito.MockSettings4import org.mockito.MockingDetails5import org.mockito.Mockito6import org.mockito.invocation.InvocationOnMock7import org.mockito.stubbing.Answer8import org.mockito.stubbing.OngoingStubbing9import org.mockito.stubbing.Stubber10import org.mockito.verification.VerificationMode11import org.mockito.verification.VerificationWithTimeout12import kotlin.reflect.KClass13/**14 *15 */16object Mocklin {17 fun atLeast(numInvocations: Int): VerificationMode = Mockito.atLeast(numInvocations)!!18 fun atLeastOnce(): VerificationMode = Mockito.atLeastOnce()!!19 fun atMost(maxNumberOfInvocations: Int): VerificationMode = Mockito.atMost(maxNumberOfInvocations)!!20 fun calls(wantedNumberOfInvocations: Int): VerificationMode = Mockito.calls(wantedNumberOfInvocations)!!21 fun <T> doAnswer(answer: (InvocationOnMock) -> T?): Stubber = Mockito.doAnswer { answer(it) }!!22 fun doCallRealMethod(): Stubber = Mockito.doCallRealMethod()!!23 fun doNothing(): Stubber = Mockito.doNothing()!!24 fun doReturn(value: Any?): Stubber = Mockito.doReturn(value)!!25 fun doThrow(toBeThrown: KClass<out Throwable>): Stubber = Mockito.doThrow(toBeThrown.java)!!26 fun <T> eq(value: T): T = Mockito.eq(value) ?: value27 fun ignoreStubs(vararg mocks: Any): Array<out Any> = Mockito.ignoreStubs(*mocks)!!28 fun inOrder(vararg mocks: Any): InOrder = Mockito.inOrder(*mocks)!!29 fun inOrder(vararg mocks: Any, evaluation: InOrder.() -> Unit) = Mockito.inOrder(*mocks).evaluation()30 fun <T : Any> isNotNull(): T? = Mockito.isNotNull() as T31 fun <T : Any> isNull(): T? = Mockito.isNull() as T32 inline fun <reified T : Any> mock(): T = Mockito.mock(T::class.java)!!33 inline fun <reified T : Any> mock(defaultAnswer: Answer<Any>): T = Mockito.mock(T::class.java, defaultAnswer)!!34 inline fun <reified T : Any> mock(s: MockSettings): T = Mockito.mock(T::class.java, s)!!35 inline fun <reified T : Any> mock(s: String): T = Mockito.mock(T::class.java, s)!!36 infix fun <T> OngoingStubbing<T>.doReturn(t: T): OngoingStubbing<T> = thenReturn(t)37 fun <T> OngoingStubbing<T>.doReturn(t: T, vararg ts: T): OngoingStubbing<T> = thenReturn(t, *ts)38 inline infix fun <reified T> OngoingStubbing<T>.doReturn(ts: List<T>): OngoingStubbing<T> = thenReturn(ts[0], *ts.drop(1).toTypedArray())39 infix fun <T> OngoingStubbing<T>.doThrow(t: Throwable): OngoingStubbing<T> = thenThrow(t)40 fun <T> OngoingStubbing<T>.doThrow(t: Throwable, vararg ts: Throwable): OngoingStubbing<T> = thenThrow(t, *ts)41 infix fun <T> OngoingStubbing<T>.doThrow(t: KClass<out Throwable>): OngoingStubbing<T> = thenThrow(t.java)42 fun <T> OngoingStubbing<T>.doThrow(t: KClass<out Throwable>, vararg ts: KClass<out Throwable>): OngoingStubbing<T> = thenThrow(t.java, *ts.map { it.java }.toTypedArray())43 fun mockingDetails(toInspect: Any): MockingDetails = Mockito.mockingDetails(toInspect)!!44 fun never(): VerificationMode = Mockito.never()!!45 fun only(): VerificationMode = Mockito.only()!!46 fun <T> refEq(value: T, vararg excludeFields: String): T? = Mockito.refEq(value, *excludeFields)47 fun <T> reset(vararg mocks: T) = Mockito.reset(*mocks)48 fun <T> same(value: T): T = Mockito.same(value) ?: value49 inline fun <reified T : Any> spy(): T = Mockito.spy(T::class.java)!!50 fun <T> spy(value: T): T = Mockito.spy(value)!!51 fun timeout(millis: Long): VerificationWithTimeout = Mockito.timeout(millis)!!52 fun times(numInvocations: Int): VerificationMode = Mockito.times(numInvocations)!!53 fun validateMockitoUsage() = Mockito.validateMockitoUsage()54 fun <T> verify(mock: T): T = Mockito.verify(mock)!!55 fun <T> verify(mock: T, mode: VerificationMode): T = Mockito.verify(mock, mode)!!56 fun <T> verifyNoMoreInteractions(vararg mocks: T) = Mockito.verifyNoMoreInteractions(*mocks)57 fun verifyZeroInteractions(vararg mocks: Any) = Mockito.verifyZeroInteractions(*mocks)58 fun <T> whenever(methodCall: T): OngoingStubbing<T> = Mockito.`when`(methodCall)!!59 fun withSettings(): MockSettings = Mockito.withSettings()!!60}...
OngoingStubbing.kt
Source:OngoingStubbing.kt
1/*2 * The MIT License3 *4 * Copyright (c) 2018 Niek Haarman5 * Copyright (c) 2007 Mockito contributors6 *7 * Permission is hereby granted, free of charge, to any person obtaining a copy8 * of this software and associated documentation files (the "Software"), to deal9 * in the Software without restriction, including without limitation the rights10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell11 * copies of the Software, and to permit persons to whom the Software is12 * furnished to do so, subject to the following conditions:13 *14 * The above copyright notice and this permission notice shall be included in15 * all copies or substantial portions of the Software.16 *17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN23 * THE SOFTWARE.24 */25package org.mockito.kotlin26import 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}...
ThenAction.kt
Source:ThenAction.kt
1/*2 * Copyright (c) 2015 Andrey Paslavsky.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 *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 }78 }79}...
StaticMocks.kt
Source:StaticMocks.kt
1/**2 * ÐÐ°Ð±Ð¾Ñ ÑаÑÑиÑений Ð´Ð»Ñ ÑÑаÑиÑеÑкиÑ
моков в ÑÑиле mockito-kotlin3 *4 * ÐÑимеÑÑ Ð¸ÑполÑзованиÑ:5 *6 * ```7 * val mock = mockStatic<SomeClass>()8 * mock.on<SomeClass, Int> { SomeClass.staticMethod() } doReturn 1119 * assertEquals(111, SomeClass.staticMethod())10 * ```11 *12 * ```13 * mockStatic<SomeClass>(){14 * on<Int> { SomeClass.staticMethod() } doReturn 11115 * }16 * assertEquals(111, SomeClass.staticMethod())17 * ```18 *19 * ÐÑли в ÑазнÑÑ
меÑодаÑ
ÑеÑÑового клаÑÑа иÑполÑзÑÑÑÑÑ ÑазнÑе моки одного и Ñого же ÑÑаÑиÑеÑкого меÑода,20 * необÑ
одимо каждÑй Ñаз закÑÑваÑÑ Ð¼Ð¾Ðº, инаÑе бÑÐ´ÐµÑ ÑкÑепÑен:21 *22 * ```23 * val myMock = mockStatic<SomeClass>()24 * // ....25 * myMock.close()26 * ```27 */28package ru.tensor.sbis.common.testing29import org.mockito.MockedStatic30import org.mockito.Mockito31import org.mockito.stubbing.OngoingStubbing32inline fun <reified T> mockStatic(): MockedStatic<T> = Mockito.mockStatic(T::class.java)33inline fun <reified T> mockStatic(init: MockStaticHelper<T>.() -> Unit): MockedStatic<T> =34 Mockito.mockStatic(T::class.java).apply {35 MockStaticHelper(this).apply(init)36 }37inline fun <T, R> MockedStatic<T>.on(crossinline call: () -> Unit): OngoingStubbing<R> = `when`<R> { call() }38infix fun <T> OngoingStubbing<T>.doReturn(value: T): OngoingStubbing<T> = thenReturn(value)39class MockStaticHelper<T>(val mock: MockedStatic<T>) {40 inline fun <R> on(crossinline call: () -> Unit): OngoingStubbing<R> = mock.`when`<R> { call() }41}...
StubbingObservableExtension.kt
Source:StubbingObservableExtension.kt
1package com.elpassion.android.commons.rxjava2.test2import com.nhaarman.mockito_kotlin.doReturn3import io.reactivex.Observable4import org.mockito.stubbing.OngoingStubbing5fun <T> OngoingStubbing<Observable<T>>.thenNever(): OngoingStubbing<Observable<T>> = thenReturn(Observable.never())6fun <T> OngoingStubbing<Observable<T>>.thenJust(value: T): OngoingStubbing<Observable<T>> = thenReturn(Observable.just(value))7fun <T> OngoingStubbing<Observable<List<T>>>.thenJust(vararg values: T): OngoingStubbing<Observable<List<T>>> = thenReturn(Observable.just(values.toList()))8fun <T> OngoingStubbing<Observable<T>>.thenError(exception: Exception = RuntimeException()): OngoingStubbing<Observable<T>> = thenReturn(Observable.error(exception))9fun <T> OngoingStubbing<Observable<T>>.doReturnJust(value: T) = doReturn(Observable.just(value))10fun <T> OngoingStubbing<Observable<List<T>>>.doReturnJust(vararg values: T) = doReturn(Observable.just(values.toList()))11fun <T> OngoingStubbing<Observable<T>>.doReturnNever() = doReturn(Observable.never())12fun <T> OngoingStubbing<Observable<T>>.doReturnError(exception: Exception = RuntimeException()) = doReturn(Observable.error(exception))...
StubbingCompletableExtension.kt
Source:StubbingCompletableExtension.kt
1package com.elpassion.android.commons.rxjava2.test2import com.nhaarman.mockito_kotlin.doReturn3import io.reactivex.Completable4import org.mockito.stubbing.OngoingStubbing5fun OngoingStubbing<Completable>.thenNever(): OngoingStubbing<Completable> = thenReturn(Completable.never())6fun OngoingStubbing<Completable>.thenError(exception: Exception = RuntimeException()): OngoingStubbing<Completable> = thenReturn(Completable.error(exception))7fun OngoingStubbing<Completable>.thenComplete(): OngoingStubbing<Completable> = thenReturn(Completable.complete())8fun OngoingStubbing<Completable>.doReturnComplete() = doReturn(Completable.complete())9fun OngoingStubbing<Completable>.doReturnNever() = doReturn(Completable.never())10fun OngoingStubbing<Completable>.doReturnError(exception: Exception = RuntimeException()) = doReturn(Completable.error(exception))...
StubbingSingleExtension.kt
Source:StubbingSingleExtension.kt
1package com.elpassion.android.commons.rxjava2.test2import com.nhaarman.mockito_kotlin.doReturn3import io.reactivex.Single4import org.mockito.stubbing.OngoingStubbing5fun <T> OngoingStubbing<Single<T>>.thenNever(): OngoingStubbing<Single<T>> = thenReturn(Single.never())6fun <T> OngoingStubbing<Single<T>>.thenJust(value: T): OngoingStubbing<Single<T>> = thenReturn(Single.just(value))7fun <T> OngoingStubbing<Single<T>>.thenError(exception: Exception = RuntimeException()): OngoingStubbing<Single<T>> = thenReturn(Single.error(exception))8fun <T> OngoingStubbing<Single<T>>.doReturnJust(value: T) = doReturn(Single.just(value))9fun <T> OngoingStubbing<Single<T>>.doReturnNever() = doReturn(Single.never())10fun <T> OngoingStubbing<Single<T>>.doReturnError(exception: Exception = RuntimeException()) = doReturn(Single.error(exception))...
OngoingStubbing.doReturn
Using AI Code Generation
1val mockedList: MutableList<String> = mock()2whenever(mockedList[0]).doReturn("first")3whenever(mockedList[1]).doReturn("second")4println(mockedList[0])5println(mockedList[1])6println(mockedList[999])7verify(mockedList)[0]8verify(mockedList)[1]9verify(mockedList)[999]10whenever(mockedList[999]).doThrow(RuntimeException())11whenever(mockedList[999]).doAnswer { throw RuntimeException() }12whenever(mockedList.get(anyInt())).doReturn("element")13whenever(mockedList.contains(argThat { isValid() })).doReturn(true)14verify(mockedList).get(anyInt())15verify(mockedList).contains(argThat { isValid() })16whenever(mockedList.contains(argThat { isValid() })).doReturn(true)17whenever(mockedList.contains(argThat { isValid() })).doReturn(true)
OngoingStubbing.doReturn
Using AI Code Generation
1doReturn(“Hello World”)2.`when`(mockedObject)3.returnString()4verify(mockedObject).returnString()5verify(mockedObject).returnStringWithArgument(any())6verify(mockedObject).returnStringWithArgument(“Hello World”)7verify(mockedObject).returnStringWithArgument(argThat { this == “Hello World” })8verify(mockedObject).returnStringWithArgument(argThat { this.length == 11 })9verify(mockedObject).returnStringWithArgument(argThat { this.startsWith(“Hello”) })10verify(mockedObject).returnStringWithArgument(argThat { this.endsWith(“World”) })11doAnswer { “Hello World” }12.`when`(mockedObject)13.returnString()14verify(mockedObject).returnString()15doThrow(NullPointerException(“Hello World”))16.`when`(mockedObject)17.returnString()18verify(mockedObject).returnString()19doNothing()20.`when`(mockedObject)21.returnString()22verify(mockedObject).returnString()23doCallRealMethod()24.`when`(mockedObject)25.returnString()26verify(mockedObject).returnString()27doAnswer { “Hello World” }28.`when`(mockedObject)29.returnStringWithArgument(“Hello World”)
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!