Best Mockito-kotlin code snippet using org.mockito.kotlin.UseConstructor
MockingTest.kt
Source:MockingTest.kt
1package test2import com.nhaarman.expect.expect3import com.nhaarman.expect.expectErrorWithMessage4import com.nhaarman.expect.fail5import org.mockito.kotlin.UseConstructor.Companion.parameterless6import org.mockito.kotlin.UseConstructor.Companion.withArguments7import org.mockito.kotlin.doReturn8import org.mockito.kotlin.mock9import org.mockito.kotlin.verify10import org.mockito.kotlin.whenever11import org.junit.Test12import org.mockito.Mockito13import org.mockito.exceptions.verification.WantedButNotInvoked14import org.mockito.invocation.DescribedInvocation15import org.mockito.kotlin.argumentCaptor16import org.mockito.listeners.InvocationListener17import org.mockito.mock.SerializableMode.BASIC18import java.io.PrintStream19import java.io.Serializable20import java.util.*...
MockitoPlugins.kt
Source:MockitoPlugins.kt
...9import com.episode6.mockspresso2.reflect.typeToken10import org.mockito.Incubating11import org.mockito.Mockito12import org.mockito.kotlin.KStubbing13import org.mockito.kotlin.UseConstructor14import org.mockito.kotlin.spy15import org.mockito.kotlin.withSettings16import org.mockito.listeners.InvocationListener17import org.mockito.mock.SerializableMode18import org.mockito.stubbing.Answer19import kotlin.reflect.KClass20/**21 * Use mockito to generate fallback objects for dependencies that are not present in the mockspresso instance22 */23fun MockspressoBuilder.fallbackWithMockito(): MockspressoBuilder =24 makeFallbackObjectsWith(object : FallbackObjectMaker {25 override fun <T> makeObject(key: DependencyKey<T>): T = Mockito.mock(key.token.asJClass())26 })27/**28 * Add a mock with the supplied params as a dependency in this mockspresso instance. Mock will be bound with the29 * supplied qualifier annotation. If you need a reference to the mock dependency, consider [MockspressoProperties.mock]30 * instead.31 */32inline fun <reified T : Any?> MockspressoBuilder.mock(33 qualifier: Annotation? = null,34 extraInterfaces: Array<out KClass<out Any>>? = null,35 name: String? = null,36 spiedInstance: Any? = null,37 defaultAnswer: Answer<Any>? = null,38 serializable: Boolean = false,39 serializableMode: SerializableMode? = null,40 verboseLogging: Boolean = false,41 invocationListeners: Array<InvocationListener>? = null,42 stubOnly: Boolean = false,43 @Incubating useConstructor: UseConstructor? = null,44 @Incubating outerInstance: Any? = null,45 @Incubating lenient: Boolean = false46): MockspressoBuilder = dependency(qualifier) {47 Mockito.mock(48 T::class.java,49 withSettings(50 extraInterfaces = extraInterfaces,51 name = name,52 spiedInstance = spiedInstance,53 defaultAnswer = defaultAnswer,54 serializable = serializable,55 serializableMode = serializableMode,56 verboseLogging = verboseLogging,57 invocationListeners = invocationListeners,58 stubOnly = stubOnly,59 useConstructor = useConstructor,60 outerInstance = outerInstance,61 lenient = lenient62 )63 )!!64}65/**66 * Add a mock with the supplied params as a dependency in this mockspresso instance. Mock will be bound with the67 * supplied qualifier annotation. If you need a reference to the mock dependency, consider [MockspressoProperties.mock]68 * instead.69 */70inline fun <reified T : Any?> MockspressoBuilder.mock(71 qualifier: Annotation? = null,72 extraInterfaces: Array<out KClass<out Any>>? = null,73 name: String? = null,74 spiedInstance: Any? = null,75 defaultAnswer: Answer<Any>? = null,76 serializable: Boolean = false,77 serializableMode: SerializableMode? = null,78 verboseLogging: Boolean = false,79 invocationListeners: Array<InvocationListener>? = null,80 stubOnly: Boolean = false,81 @Incubating useConstructor: UseConstructor? = null,82 @Incubating outerInstance: Any? = null,83 @Incubating lenient: Boolean = false,84 noinline stubbing: KStubbing<T>.(T) -> Unit85): MockspressoBuilder = dependency(qualifier) {86 Mockito.mock(87 T::class.java,88 withSettings(89 extraInterfaces = extraInterfaces,90 name = name,91 spiedInstance = spiedInstance,92 defaultAnswer = defaultAnswer,93 serializable = serializable,94 serializableMode = serializableMode,95 verboseLogging = verboseLogging,96 invocationListeners = invocationListeners,97 stubOnly = stubOnly,98 useConstructor = useConstructor,99 outerInstance = outerInstance,100 lenient = lenient101 )102 ).apply { KStubbing(this).stubbing(this) }!!103}104/**105 * Add a mock with the supplied params as a dependency in this mockspresso instance. Mock will be bound with the106 * supplied qualifier annotation and will be accessible via the returned lazy.107 */108inline fun <reified T : Any?> MockspressoProperties.mock(109 qualifier: Annotation? = null,110 extraInterfaces: Array<out KClass<out Any>>? = null,111 name: String? = null,112 spiedInstance: Any? = null,113 defaultAnswer: Answer<Any>? = null,114 serializable: Boolean = false,115 serializableMode: SerializableMode? = null,116 verboseLogging: Boolean = false,117 invocationListeners: Array<InvocationListener>? = null,118 stubOnly: Boolean = false,119 @Incubating useConstructor: UseConstructor? = null,120 @Incubating outerInstance: Any? = null,121 @Incubating lenient: Boolean = false122): Lazy<T> = dependency(qualifier) {123 Mockito.mock(124 T::class.java,125 withSettings(126 extraInterfaces = extraInterfaces,127 name = name,128 spiedInstance = spiedInstance,129 defaultAnswer = defaultAnswer,130 serializable = serializable,131 serializableMode = serializableMode,132 verboseLogging = verboseLogging,133 invocationListeners = invocationListeners,134 stubOnly = stubOnly,135 useConstructor = useConstructor,136 outerInstance = outerInstance,137 lenient = lenient138 )139 )!!140}141/**142 * Add a mock with the supplied params as a dependency in this mockspresso instance. Mock will be bound with the143 * supplied qualifier annotation and will be accessible via the returned lazy.144 */145inline fun <reified T : Any?> MockspressoProperties.mock(146 qualifier: Annotation? = null,147 extraInterfaces: Array<out KClass<out Any>>? = null,148 name: String? = null,149 spiedInstance: Any? = null,150 defaultAnswer: Answer<Any>? = null,151 serializable: Boolean = false,152 serializableMode: SerializableMode? = null,153 verboseLogging: Boolean = false,154 invocationListeners: Array<InvocationListener>? = null,155 stubOnly: Boolean = false,156 @Incubating useConstructor: UseConstructor? = null,157 @Incubating outerInstance: Any? = null,158 @Incubating lenient: Boolean = false,159 noinline stubbing: KStubbing<T>.(T) -> Unit160): Lazy<T> = dependency(qualifier) {161 Mockito.mock(162 T::class.java,163 withSettings(164 extraInterfaces = extraInterfaces,165 name = name,166 spiedInstance = spiedInstance,167 defaultAnswer = defaultAnswer,168 serializable = serializable,169 serializableMode = serializableMode,170 verboseLogging = verboseLogging,...
AemArticleManagerTest.kt
Source:AemArticleManagerTest.kt
...17import org.junit.runner.RunWith18import org.mockito.Mockito.CALLS_REAL_METHODS19import org.mockito.Mockito.RETURNS_DEEP_STUBS20import org.mockito.Mockito.verifyNoInteractions21import org.mockito.kotlin.UseConstructor22import org.mockito.kotlin.any23import org.mockito.kotlin.doReturn24import org.mockito.kotlin.eq25import org.mockito.kotlin.mock26import org.mockito.kotlin.never27import org.mockito.kotlin.stub28import org.mockito.kotlin.verify29import org.mockito.kotlin.verifyNoMoreInteractions30import org.mockito.kotlin.whenever31import retrofit2.Response32@RunWith(AndroidJUnit4::class)33@OptIn(ExperimentalCoroutinesApi::class)34class AemArticleManagerTest {35 private lateinit var aemDb: ArticleRoomDatabase36 private lateinit var api: AemApi37 private lateinit var fileManager: AemArticleManager.FileManager38 private lateinit var manifestManager: ManifestManager39 private val testScope = TestScope()40 private lateinit var articleManager: AemArticleManager41 @Before42 fun setup() {43 aemDb = mock(defaultAnswer = RETURNS_DEEP_STUBS) {44 onBlocking { resourceDao().getAll() } doReturn emptyList()45 }46 api = mock()47 fileManager = mock()48 manifestManager = mock()49 articleManager = mock(50 defaultAnswer = CALLS_REAL_METHODS,51 useConstructor = UseConstructor.withArguments(aemDb, api, fileManager, manifestManager, testScope)52 )53 }54 // region Translations55 @Test56 fun `processDownloadedTranslations()`() = testScope.runTest {57 val translation = mock<Translation>()58 val translations = listOf(translation)59 val uri = mock<Uri>()60 val manifest = mock<Manifest> { on { aemImports } doReturn listOf(uri) }61 val repository = aemDb.translationRepository().stub {62 onBlocking { isProcessed(any()) } doReturn false63 }64 whenever(manifestManager.getManifest(translation)) doReturn manifest65 whenever(articleManager.syncAemImportsFromManifest(any(), any())) doReturn null...
MockitoCodeGenerator.kt
Source:MockitoCodeGenerator.kt
...19 "MockitoJUnit" to "org.mockito.junit.MockitoJUnit",20 "Mock" to "org.mockito.Mock",21 "mock" to "org.mockito.kotlin.mock",22 "Mockito" to "org.mockito.Mockito",23 "UseConstructor" to "org.mockito.kotlin.UseConstructor"24 ) + super.knownImports25 override val setUpStatements: String? = null26 override fun reset() {27 _requiredImports.clear()28 }29 override fun getConstructorMock(parameterName: String, parameterType: DataType) =30 "${indent()}@Mock\n" +31 "${indent()}lateinit var $parameterName: ${parameterType.toNonNullableKotlinString()}"32 override fun getMockedInstance(variableType: DataType) =33 "mock<${variableType.toNonNullableKotlinString()}>()"34 override fun getAbstractClassUnderTest(classUnderTest: ClassMetadata) =35 "mock(defaultAnswer = Mockito.CALLS_REAL_METHODS${constructorArgumentsForAbstract(classUnderTest)})"36 override fun setIsParameterizedTest() {37 super.setIsParameterizedTest()38 isParameterizedTest = true39 addMockRuleIfNeeded()40 }41 override fun setHasMockedConstructorParameters(classUnderTest: ClassMetadata) {42 _requiredImports.add("RunWith")43 _requiredImports.add("MockitoJUnitRunner")44 _requiredImports.add("Mock")45 if (classUnderTest.isAbstract && classUnderTest.constructorParameters.isNotEmpty()) {46 _requiredImports.add("UseConstructor")47 }48 hasMockedConstructorParameters = true49 addMockRuleIfNeeded()50 }51 private fun addMockRuleIfNeeded() {52 if (isParameterizedTest && hasMockedConstructorParameters) {53 _requiredImports.add("Rule")54 _requiredImports.add("MethodRule")55 _requiredImports.add("MockitoJUnit")56 }57 }58 override fun setHasMockedFunctionParameters() {59 setInstantiatesMocks()60 }61 override fun setHasMockedFunctionReturnValues() {62 setInstantiatesMocks()63 }64 override fun setIsAbstractClassUnderTest() {65 setInstantiatesMocks()66 _requiredImports.add("Mockito")67 }68 private fun setInstantiatesMocks() {69 _requiredImports.add("mock")70 }71 private fun constructorArgumentsForAbstract(classUnderTest: ClassMetadata) =72 if (classUnderTest.constructorParameters.isEmpty()) {73 ""74 } else {75 val arguments =76 classUnderTest.constructorParameters.joinToString(", ") { parameter -> parameter.name }77 ", useConstructor = UseConstructor.withArguments($arguments)"78 }79}...
ItemDaoHelperTest.kt
Source:ItemDaoHelperTest.kt
...9import org.junit.runner.RunWith10import org.mockito.Mock11import org.mockito.Mockito.verify12import org.mockito.junit.MockitoJUnitRunner13import org.mockito.kotlin.UseConstructor14import org.mockito.kotlin.mock15@OptIn(ExperimentalCoroutinesApi::class)16@RunWith(MockitoJUnitRunner::class)17class ItemDaoHelperTest {18 @Mock19 lateinit var pagingDao: BaseGetPagingSourceDao<Any>20 @Mock21 lateinit var itemDao: BaseDao<Any>22 @Mock23 lateinit var remoteKeyDao: RemoteKeyDao24 private val mockTransactionManager = MockTransactionManager()25 @Test26 fun `save valid items and remoteKeys verify functions usage`() = runTest {27 val daoHelper = getSaveItemsWithRemoteKeysDaoHelper()28 val items = EmulatedData.characterList29 val remoteKeys = EmulatedData.remoteKeyList30 daoHelper.save(items, remoteKeys)31 verify(itemDao).insertItems(items)32 verify(remoteKeyDao).insertItems(remoteKeys)33 }34 @Test35 fun `save empty data verify all functions triggered`() = runTest {36 val daoHelper = getSaveItemsWithRemoteKeysDaoHelper()37 daoHelper.save(emptyList(), emptyList())38 verify(itemDao).insertItems(emptyList())39 verify(remoteKeyDao).insertItems(emptyList())40 }41 @Test(expected = IllegalArgumentException::class)42 fun `save items and remoteKeys with different data size throws exception`() = runTest {43 val daoHelper = getSaveItemsWithRemoteKeysDaoHelper()44 daoHelper.save(EmulatedData.characterList, emptyList())45 }46 private fun getSaveItemsWithRemoteKeysDaoHelper() : SaveItemsWithRemoteKeysDaoHelper<Any> =47 mock(useConstructor = UseConstructor.withArguments(48 itemDao, remoteKeyDao, mockTransactionManager49 ))50 @Test51 fun `clear item dao and remoteKey dao`() = runTest {52 val clearDaoHelper = ClearAllItemsAndKeysDaoHelper(itemDao, remoteKeyDao, mockTransactionManager)53 clearDaoHelper.clearTables()54 verify(itemDao).clear()55 verify(remoteKeyDao).clear()56 }57 @Test58 fun `get paging source`() = runTest {59 val pagingDaoHelper: GetPagingSourceDaoHelper<Any> = mock(60 useConstructor = UseConstructor.withArguments(pagingDao)61 )62 pagingDaoHelper.getPagingSource()63 verify(pagingDao).getPagingSource()64 }65}...
FeedActivityTests.kt
Source:FeedActivityTests.kt
...20import org.koin.core.module.Module21import org.koin.dsl.module22import org.koin.test.KoinTest23import org.koin.test.get24import org.mockito.kotlin.UseConstructor25import org.mockito.kotlin.mock26/**27 * Created by Vdovicenco Alexandr on 04/19/2021.28 */29@RunWith(AndroidJUnit4::class)30class FeedActivityTests: KoinTest {31 lateinit var mockModule: Module32 @Before33 fun setup() {34 mockModule = module(override = true) {35 single<FeedOutput>(override = true) { (view: FeedInput) ->36 mock<FeedPresenter>(useConstructor = UseConstructor.withArguments(view, get<APIClient>()))37 }38 single<APIClient> { mock() }39 }40 loadKoinModules(mockModule)41 }42 @After43 fun tearDown() {44 unloadKoinModules(mockModule)45 }46 @Test47 fun checkFeedLoading() {48 val feedItemStub = FeedItem("", null, null)49 ActivityScenario.launch(FeedActivity::class.java)50 // Init expected result...
AuthActivityTest.kt
Source:AuthActivityTest.kt
...15import org.junit.runner.RunWith16import org.koin.core.context.GlobalContext.loadKoinModules17import org.koin.core.module.Module18import org.koin.dsl.module19import org.mockito.kotlin.UseConstructor20import org.mockito.kotlin.mock21@RunWith(AndroidJUnit4::class)22class AuthActivityTest: TestCase() {23 lateinit var mockModule: Module24 @Before25 fun setup() {26 mockModule = module(override = true) {27 single<AuthOutput>(override = true) { (view: AuthInput) ->28 mock<AuthPresenter>(useConstructor = UseConstructor.withArguments(view, get<APIClient>()))29 }30 single<APIClient> { mock() }31 }32 loadKoinModules(mockModule)33 }34 @get:Rule35 val activityRule = ActivityScenarioRule(AuthActivity::class.java)36 @Test37 fun test_validateEditText() {38 onView(withId(R.id.userLogin)).perform(typeText("test-string")).check(matches(withText("test-string")))39 }40}...
Mocking.kt
Source:Mocking.kt
...15 */16package org.wfanet.measurement.common.grpc.testing17import io.grpc.kotlin.AbstractCoroutineServerImpl18import org.mockito.kotlin.KStubbing19import org.mockito.kotlin.UseConstructor20import org.mockito.kotlin.mock21/** Creates a mock for a gRPC coroutine service [T], allowing for immediate stubbing. */22inline fun <reified T : AbstractCoroutineServerImpl> mockService(23 stubbing: KStubbing<T>.(T) -> Unit24): T =25 mock(useConstructor = UseConstructor.parameterless()) { mock ->26 on { context }.thenCallRealMethod()27 stubbing(mock)28 }29/** Creates a mock for a gRPC coroutine service [T]. */30inline fun <reified T : AbstractCoroutineServerImpl> mockService(): T =31 mock(useConstructor = UseConstructor.parameterless()) { on { context }.thenCallRealMethod() }...
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!!