I'm trying to inject dependencies into a subclass of FirebaseInstanceIdService, but I'm getting a compile time exception that is very vague.
EDIT: When I comment out the inject method declaration, it compiles.
AppComponent:
#Singleton
#Component(modules = [AppModule::class, ApiModule::class])
interface AppComponent {
fun inject(app: MyApplication)
fun plus(someModule: SomeModule): SomeComponent
/* omitting others for sake of brevity */
//If I comment this one out, the project compiles and runs
fun plus(firebaseInstanceModule: FirebaseInstanceModule): FirebaseInstanceComponent
}
Module:
#Module
class FirebaseInstanceModule {
#Provides
fun providePresenter(userService: UserService): PushPresenter =
PushPresenterImpl(userService)
}
Component:
#Subcomponent(modules = [(FirebaseInstanceModule::class)])
interface FirebaseInstanceComponent {
//Commenting out this method, the project compiles
fun inject(service: MyFirebaseInstanceIdService)
}
Service:
class MyFirebaseInstanceIdService : FirebaseInstanceIdService() {
private val TAG = "FirebaseInstanceId"
#Inject
lateinit var pushPresenter: PushPresenter
override fun onCreate() {
Log.d(TAG, "onCreate")
mainApplication.appComponent.plus(FirebaseInstanceModule()).inject(this)
}
override fun onTokenRefresh() {
Log.d(TAG, "onTokenRefresh")
val token = FirebaseInstanceId.getInstance().token
token?.let { pushPresenter.updateToken(it) }
}
}
Stack trace:
e: java.lang.IllegalStateException: failed to analyze: java.lang.IllegalArgumentException
at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:137)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:158)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:61)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:107)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51)
at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:386)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:96)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:892)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:919)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:891)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:385)
at sun.reflect.GeneratedMethodAccessor91.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:324)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:108)
at dagger.internal.codegen.writer.ClassName.peerNamed(ClassName.java:130)
at dagger.internal.codegen.SourceFiles.membersInjectorNameForMembersInjectionBinding(SourceFiles.java:266)
at dagger.internal.codegen.InjectBindingRegistry.registerBinding(InjectBindingRegistry.java:199)
at dagger.internal.codegen.InjectBindingRegistry.getOrFindMembersInjectionBinding(InjectBindingRegistry.java:261)
at dagger.internal.codegen.BindingGraph$Factory$RequestResolver.rollUpMembersInjectionBindings(BindingGraph.java:374)
at dagger.internal.codegen.BindingGraph$Factory$RequestResolver.rollUpMembersInjectionBindings(BindingGraph.java:378)
at dagger.internal.codegen.BindingGraph$Factory$RequestResolver.lookUpBindings(BindingGraph.java:366)
at dagger.internal.codegen.BindingGraph$Factory$RequestResolver.resolve(BindingGraph.java:461)
at dagger.internal.codegen.BindingGraph$Factory$RequestResolver.resolve(BindingGraph.java:464)
at dagger.internal.codegen.BindingGraph$Factory.create(BindingGraph.java:228)
at dagger.internal.codegen.BindingGraph$Factory.create(BindingGraph.java:236)
at dagger.internal.codegen.BindingGraph$Factory.create(BindingGraph.java:151)
at dagger.internal.codegen.ComponentProcessingStep.process(ComponentProcessingStep.java:76)
at dagger.shaded.auto.common.BasicAnnotationProcessor.process(BasicAnnotationProcessor.java:228)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:794)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:705)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$1800(JavacProcessingEnvironment.java:91)
at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1035)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1176)
at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1170)
at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1068)
at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:73)
at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:42)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:205)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:166)
at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:82)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:96)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:106)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:83)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:376)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:67)
at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:96)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:367)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:132)
... 29 more
Related
Writing unit test to insert object to room database, take it from database and assert are the 2 mentioned equal. Here is the code:
#RunWith(AndroidJUnit4::class)
#SmallTest
class GdprDaoTest {
private lateinit var dao: GdprDao
private lateinit var database: AppDatabase
#get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
#Before
fun setup() {
database = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
AppDatabase::class.java
).allowMainThreadQueries().build()
dao = database.gdprDao()
}
#Test
fun insertConfiguration(){
runBlocking {
val insertedGdprEntity =
GdprEntity(id = 1, conditionsUrl = "conditionsUrl", agreementUrl = "AgreementUrl")
dao.insert(insertedGdprEntity)
var fetchedGdprEntity = dao.getGdpr().getOrAwaitValue()
assertEquals(insertedGdprEntity, fetchedGdprEntity)
}
}
#After
fun tearDown() {
database.close()
}
}
But this does not work. When I debug, it fails on the line dao.insert(insertedGdprEntity). In debug I can see that do is instantiated (it is not null). Looks pretty straight forward code to me, am I missing something? Here is the error I get from stacktrace:
System.logW: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.java.lang.Throwable: Explicit termination method 'close' not called
com.almworks.sqlite4java.SQLiteException: [-91] cannot load library: java.lang.UnsatisfiedLinkError: Can't load library: /var/folders/2v/mk_0n_7d2tgc3hnv9kr4t57w0000gn/T/1674396103129-0/libsqlite4java.dylib
java.lang.RuntimeException: com.almworks.sqlite4java.SQLiteException: [-91] cannot load library: java.lang.UnsatisfiedLinkError: Can't load library: /var/folders/2v/mk_0n_7d2tgc3hnv9kr4t57w0000gn/T/1674396103129-0/libsqlite4java.dylib
at org.robolectric.shadows.util.SQLiteLibraryLoader.loadFromDirectory(SQLiteLibraryLoader.java:92)
at org.robolectric.shadows.util.SQLiteLibraryLoader.doLoad(SQLiteLibraryLoader.java:55)
at org.robolectric.shadows.util.SQLiteLibraryLoader.load(SQLiteLibraryLoader.java:39)
at org.robolectric.shadows.ShadowSQLiteConnection.nativeOpen(ShadowSQLiteConnection.java:73)
at android.database.sqlite.SQLiteConnection.nativeOpen(SQLiteConnection.java)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
at android.database.sqlite.SQLiteDatabase.create(SQLiteDatabase.java:826)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:216)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:151)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:112)
at androidx.room.RoomDatabase.internalBeginTransaction(RoomDatabase.java:566)
at androidx.room.RoomDatabase.beginTransaction(RoomDatabase.java:555)
at fortuna.vegas.android.data.local.database.dao.GdprDao_Impl$3.call(GdprDao_Impl.java:73)
at fortuna.vegas.android.data.local.database.dao.GdprDao_Impl$3.call(GdprDao_Impl.java:70)
at androidx.room.CoroutinesRoom$Companion$execute$2.invokeSuspend(CoroutinesRoom.kt:65)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:47)
at androidx.arch.core.executor.testing.InstantTaskExecutorRule$1.executeOnDiskIO(InstantTaskExecutorRule.java:38)
at androidx.arch.core.executor.ArchTaskExecutor.executeOnDiskIO(ArchTaskExecutor.java:96)
at androidx.arch.core.executor.ArchTaskExecutor$2.execute(ArchTaskExecutor.java:53)
at androidx.room.TransactionExecutor.scheduleNext(TransactionExecutor.java:61)
at androidx.room.TransactionExecutor.execute(TransactionExecutor.java:54)
at kotlinx.coroutines.ExecutorCoroutineDispatcherImpl.dispatch(Executors.kt:128)
at kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:322)
at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30)
at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:25)
at kotlinx.coroutines.BuildersKt__Builders_commonKt.withContext(Builders.common.kt:171)
at kotlinx.coroutines.BuildersKt.withContext(Unknown Source)
at androidx.room.CoroutinesRoom$Companion.execute(CoroutinesRoom.kt:64)
at androidx.room.CoroutinesRoom.execute(CoroutinesRoom.kt)
at fortuna.vegas.android.data.local.database.dao.GdprDao_Impl.insert(GdprDao_Impl.java:70)
at fortuna.vegas.android.GdprDaoTest$insertConfiguration$1.invokeSuspend(GdprDaoTest.kt:55)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:279)
at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:85)
at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:59)
at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:38)
at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
at fortuna.vegas.android.GdprDaoTest.insertConfiguration(GdprDaoTest.kt:52)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:61)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.robolectric.RobolectricTestRunner$HelperTestRunner$1.evaluate(RobolectricTestRunner.java:575)
at org.robolectric.internal.SandboxTestRunner$2.lambda$evaluate$0(SandboxTestRunner.java:278)
at org.robolectric.internal.bytecode.Sandbox.lambda$runOnMainThread$0(Sandbox.java:89)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: com.almworks.sqlite4java.SQLiteException: [-91] cannot load library: java.lang.UnsatisfiedLinkError: Can't load library: /var/folders/2v/mk_0n_7d2tgc3hnv9kr4t57w0000gn/T/1674396103129-0/libsqlite4java.dylib
at app//com.almworks.sqlite4java.SQLite.loadLibrary(SQLite.java:97)
at app//com.almworks.sqlite4java.SQLite.getSQLiteVersion(SQLite.java:114)
at org.robolectric.shadows.util.SQLiteLibraryLoader.loadFromDirectory(SQLiteLibraryLoader.java:90)
at org.robolectric.shadows.util.SQLiteLibraryLoader.doLoad(SQLiteLibraryLoader.java:55)
at org.robolectric.shadows.util.SQLiteLibraryLoader.load(SQLiteLibraryLoader.java:39)
at org.robolectric.shadows.ShadowSQLiteConnection.nativeOpen(ShadowSQLiteConnection.java:73)
at android.database.sqlite.SQLiteConnection.nativeOpen(SQLiteConnection.java)
at android.database.sqlite.SQLiteConnection.$$robo$$android_database_sqlite_SQLiteConnection$open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java)
at android.database.sqlite.SQLiteConnection.$$robo$$android_database_sqlite_SQLiteConnection$open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java)
at android.database.sqlite.SQLiteConnectionPool.$$robo$$android_database_sqlite_SQLiteConnectionPool$openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java)
at android.database.sqlite.SQLiteConnectionPool.$$robo$$android_database_sqlite_SQLiteConnectionPool$open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java)
at android.database.sqlite.SQLiteConnectionPool.$$robo$$android_database_sqlite_SQLiteConnectionPool$open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java)
at android.database.sqlite.SQLiteDatabase.$$robo$$android_database_sqlite_SQLiteDatabase$openInner(SQLiteDatabase.java:804)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java)
at android.database.sqlite.SQLiteDatabase.$$robo$$android_database_sqlite_SQLiteDatabase$open(SQLiteDatabase.java:789)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java)
at android.database.sqlite.SQLiteDatabase.$$robo$$android_database_sqlite_SQLiteDatabase$openDatabase(SQLiteDatabase.java:694)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java)
at android.database.sqlite.SQLiteDatabase.$$robo$$android_database_sqlite_SQLiteDatabase$openDatabase(SQLiteDatabase.java:669)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java)
at android.database.sqlite.SQLiteDatabase.$$robo$$android_database_sqlite_SQLiteDatabase$create(SQLiteDatabase.java:826)
at android.database.sqlite.SQLiteDatabase.create(SQLiteDatabase.java)
at android.database.sqlite.SQLiteOpenHelper.$$robo$$android_database_sqlite_SQLiteOpenHelper$getDatabaseLocked(SQLiteOpenHelper.java:216)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java)
at android.database.sqlite.SQLiteOpenHelper.$$robo$$android_database_sqlite_SQLiteOpenHelper$getWritableDatabase(SQLiteOpenHelper.java:164)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.$$robo$$androidx_sqlite_db_framework_FrameworkSQLiteOpenHelper_OpenHelper$getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:151)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.$$robo$$androidx_sqlite_db_framework_FrameworkSQLiteOpenHelper$getWritableDatabase(FrameworkSQLiteOpenHelper.java:112)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java)
at androidx.room.RoomDatabase.internalBeginTransaction(RoomDatabase.java:566)
at androidx.room.RoomDatabase.beginTransaction(RoomDatabase.java:555)
at fortuna.vegas.android.data.local.database.dao.GdprDao_Impl$3.call(GdprDao_Impl.java:73)
at fortuna.vegas.android.data.local.database.dao.GdprDao_Impl$3.call(GdprDao_Impl.java:70)
at androidx.room.CoroutinesRoom$Companion$execute$2.invokeSuspend(CoroutinesRoom.kt:65)
at app//kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:47)
at androidx.arch.core.executor.testing.InstantTaskExecutorRule$1.executeOnDiskIO(InstantTaskExecutorRule.java:38)
at androidx.arch.core.executor.ArchTaskExecutor.executeOnDiskIO(ArchTaskExecutor.java:96)
at androidx.arch.core.executor.ArchTaskExecutor$2.execute(ArchTaskExecutor.java:53)
at androidx.room.TransactionExecutor.scheduleNext(TransactionExecutor.java:61)
at androidx.room.TransactionExecutor.execute(TransactionExecutor.java:54)
at kotlinx.coroutines.ExecutorCoroutineDispatcherImpl.dispatch(Executors.kt:128)
at kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:322)
at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30)
at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:25)
at kotlinx.coroutines.BuildersKt__Builders_commonKt.withContext(Builders.common.kt:171)
at kotlinx.coroutines.BuildersKt.withContext(Unknown Source)
at androidx.room.CoroutinesRoom$Companion.execute(CoroutinesRoom.kt:64)
at androidx.room.CoroutinesRoom.execute(CoroutinesRoom.kt)
at fortuna.vegas.android.data.local.database.dao.GdprDao_Impl.insert(GdprDao_Impl.java:70)
at fortuna.vegas.android.GdprDaoTest$insertConfiguration$1.invokeSuspend(GdprDaoTest.kt:55)
at app//kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:279)
at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:85)
at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:59)
at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:38)
at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
at fortuna.vegas.android.GdprDaoTest.insertConfiguration(GdprDaoTest.kt:52)
at java.base#11.0.15/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base#11.0.15/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base#11.0.15/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base#11.0.15/java.lang.reflect.Method.invoke(Method.java:566)
... 15 more
Caused by: java.lang.UnsatisfiedLinkError: Can't load library: /var/folders/2v/mk_0n_7d2tgc3hnv9kr4t57w0000gn/T/1674396103129-0/libsqlite4java.dylib
at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2633)
at java.base/java.lang.Runtime.load0(Runtime.java:768)
at java.base/java.lang.System.load(System.java:1837)
at com.almworks.sqlite4java.Internal.tryLoadFromPath(Internal.java:340)
at com.almworks.sqlite4java.Internal.loadLibraryX(Internal.java:110)
at com.almworks.sqlite4java.SQLite.loadLibrary(SQLite.java:95)
... 85 more
As already discussed the solution is to increase the version of robolectric to 4.9 as described in this issue https://github.com/robolectric/robolectric/issues/7590
All that is needed to be done is update to:
testImplementation "org.robolectric:robolectric:4.9"
And:
testOptions { unitTests.includeAndroidResources = true }
I am trying to mock this function below by using Mockk library.
fun launchOn(block: suspend CoroutineScope.() -> Unit) {
viewModelScope.launch(Dispatchers.IO) { block() }
}
I tried to mock following below
private val viewModel: PersonalInfoViewModel = mockk(relaxed = true)
every { viewModel.launchOn(any()) } answers {callOriginal()}
but I am getting ClassCastException. I also tried to use coEvery and hint but nothing changed. I could not find much information about this situation in documentations.
My questions are, Where did i make mistake? What is the proper way to mock this function?
Thanks
Exception:
class java.lang.Object cannot be cast to class kotlinx.coroutines.CoroutineScope (java.lang.Object is in module java.base of loader 'bootstrap'; kotlinx.coroutines.CoroutineScope is in unnamed module of loader org.robolectric.internal.AndroidSandbox$SdkSandboxClassLoader #17490d9e)
java.lang.ClassCastException: class java.lang.Object cannot be cast to class kotlinx.coroutines.CoroutineScope (java.lang.Object is in module java.base of loader 'bootstrap'; kotlinx.coroutines.CoroutineScope is in unnamed module of loader org.robolectric.internal.AndroidSandbox$SdkSandboxClassLoader #17490d9e)
at androidx.lifecycle.ViewModelKt.getViewModelScope(ViewModel.kt:37)
at com.biletdukkani.common.base.BaseViewModel.launchOn(BaseViewModel.kt:106)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at io.mockk.proxy.jvm.advice.MethodCall.call(MethodCall.kt:14)
at io.mockk.proxy.jvm.advice.SelfCallEliminatorCallable.call(SelfCallEliminatorCallable.kt:14)
at io.mockk.impl.instantiation.JvmMockFactoryHelper.handleOriginalCall(JvmMockFactoryHelper.kt:83)
at io.mockk.impl.instantiation.JvmMockFactoryHelper.access$handleOriginalCall(JvmMockFactoryHelper.kt:20)
at io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1$invocation$$inlined$stdFunctions$lambda$1.invoke(JvmMockFactoryHelper.kt:28)
at io.mockk.impl.stub.MockKStub$handleInvocation$originalPlusToString$1.invoke(MockKStub.kt:227)
at io.mockk.MockKAnswerScope.callOriginal(API.kt:2184)
at com.biletdukkani.b2c.fragments.personalInfo.PersonalInfoViewModelTest$initViewModelFunctions$2.invoke(PersonalInfoViewModelTest.kt:57)
at com.biletdukkani.b2c.fragments.personalInfo.PersonalInfoViewModelTest$initViewModelFunctions$2.invoke(PersonalInfoViewModelTest.kt:57)
at io.mockk.MockKStubScope$answers$1.invoke(API.kt:2092)
at io.mockk.MockKStubScope$answers$1.invoke(API.kt:2069)
at io.mockk.FunctionAnswer.answer(Answers.kt:19)
at io.mockk.impl.stub.AnswerAnsweringOpportunity.answer(AnswerAnsweringOpportunity.kt:14)
at io.mockk.impl.stub.MockKStub.answer(MockKStub.kt:54)
at io.mockk.impl.recording.states.AnsweringState.call(AnsweringState.kt:16)
at io.mockk.impl.recording.CommonCallRecorder.call(CommonCallRecorder.kt:53)
at io.mockk.impl.stub.MockKStub.handleInvocation(MockKStub.kt:263)
at io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1.invocation(JvmMockFactoryHelper.kt:25)
at io.mockk.proxy.jvm.advice.Interceptor.call(Interceptor.kt:20)
at com.biletdukkani.common.base.BaseViewModel.launchOn(BaseViewModel.kt:107)
at com.biletdukkani.b2c.fragments.personalInfo.PersonalInfoViewModel.getProfileInfo(PersonalInfoViewModel.kt:18)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at io.mockk.proxy.jvm.advice.MethodCall.call(MethodCall.kt:14)
at io.mockk.proxy.jvm.advice.SelfCallEliminatorCallable.call(SelfCallEliminatorCallable.kt:14)
at io.mockk.impl.instantiation.JvmMockFactoryHelper.handleOriginalCall(JvmMockFactoryHelper.kt:83)
at io.mockk.impl.instantiation.JvmMockFactoryHelper.access$handleOriginalCall(JvmMockFactoryHelper.kt:20)
at io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1$invocation$$inlined$stdFunctions$lambda$1.invoke(JvmMockFactoryHelper.kt:28)
at io.mockk.impl.stub.MockKStub$handleInvocation$originalPlusToString$1.invoke(MockKStub.kt:227)
at io.mockk.MockKAnswerScope.callOriginal(API.kt:2184)
at com.biletdukkani.b2c.fragments.personalInfo.PersonalInfoViewModelTest$initViewModelFunctions$6.invoke(PersonalInfoViewModelTest.kt:59)
at com.biletdukkani.b2c.fragments.personalInfo.PersonalInfoViewModelTest$initViewModelFunctions$6.invoke(PersonalInfoViewModelTest.kt:59)
at io.mockk.MockKStubScope$answers$1.invoke(API.kt:2092)
at io.mockk.MockKStubScope$answers$1.invoke(API.kt:2069)
at io.mockk.FunctionAnswer.answer(Answers.kt:19)
at io.mockk.impl.stub.AnswerAnsweringOpportunity.answer(AnswerAnsweringOpportunity.kt:14)
at io.mockk.impl.stub.MockKStub.answer(MockKStub.kt:54)
at io.mockk.impl.recording.states.AnsweringState.call(AnsweringState.kt:16)
at io.mockk.impl.recording.CommonCallRecorder.call(CommonCallRecorder.kt:53)
at io.mockk.impl.stub.MockKStub.handleInvocation(MockKStub.kt:263)
at io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1.invocation(JvmMockFactoryHelper.kt:25)
at io.mockk.proxy.jvm.advice.Interceptor.call(Interceptor.kt:20)
at com.biletdukkani.b2c.fragments.personalInfo.PersonalInfoViewModel.getProfileInfo(PersonalInfoViewModel.kt:32)
at com.biletdukkani.b2c.fragments.personalInfo.PersonalInfoViewModelTest.getProfileInfo(PersonalInfoViewModelTest.kt:72)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:61)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:61)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.robolectric.RobolectricTestRunner$HelperTestRunner$1.evaluate(RobolectricTestRunner.java:575)
at org.robolectric.internal.SandboxTestRunner$2.lambda$evaluate$0(SandboxTestRunner.java:278)
at org.robolectric.internal.bytecode.Sandbox.lambda$runOnMainThread$0(Sandbox.java:89)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
I figured it out.
I split my function in 2 parts. Then, I mocked executeProfileInfoGet part. Now, I don't need to mock launchOn function anymore.
functions:
fun getProfileInfo() = launchOn {
executeProfileInfoGet()
}
suspend fun executeProfileInfoGet(){
executeFlow(profileInfoRepository.getProfileInfo()) {
when (it) {
is DataState.Success -> {
initCaches(it.response)
checkPassportFields(it.response)
profileInfoLiveData.postValue(it.response)
}
is DataState.Error -> {
showError(it.error.message)
}
else -> Unit
}
}
}
mocked in test class:
coEvery { viewModel.executeProfileInfoGet() } coAnswers { callOriginal() }
I'm trying to implement Scabbard to my project which is visualize dagger dependencies. I've followed the steps of its home page. but when I tried to build the project, it fails as shown below. I'll also add part of my Gradle. Actually, when I add the scabbard configuration part, it starts to fail. Implementation of other I guess doesn't cause this
buildscript {
repositories {
jcenter()
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath "gradle.plugin.dev.arunkumar:scabbard-gradle-plugin:0.4.0"
}
}
apply plugin: "scabbard.gradle"
scabbard {
enabled true // default false
outputFormat "svg" // default png
}
My error message is :
e: [kapt] An exception occurred: java.lang.NoSuchFieldError: RELEASABLE_REFERENCE_MANAGER
at dagger.internal.codegen.BindingDeclarationFormatter.<clinit>(BindingDeclarationFormatter.java:47)
at dagger.internal.codegen.DaggerComponentProcessor_ProcessorComponent.getBindingDeclarationFormatter(DaggerComponentProcessor_ProcessorComponent.java:379)
at dagger.internal.codegen.DaggerComponentProcessor_ProcessorComponent.getBindingGraphConverter(DaggerComponentProcessor_ProcessorComponent.java:383)
at dagger.internal.codegen.DaggerComponentProcessor_ProcessorComponent.getComponentProcessingStep(DaggerComponentProcessor_ProcessorComponent.java:396)
at dagger.internal.codegen.DaggerComponentProcessor_ProcessorComponent.getImmutableListOfProcessingStep(DaggerComponentProcessor_ProcessorComponent.java:486)
at dagger.internal.codegen.DaggerComponentProcessor_ProcessorComponent.injectComponentProcessor(DaggerComponentProcessor_ProcessorComponent.java:634)
at dagger.internal.codegen.DaggerComponentProcessor_ProcessorComponent.inject(DaggerComponentProcessor_ProcessorComponent.java:623)
at dagger.internal.codegen.ComponentProcessor.initSteps(ComponentProcessor.java:105)
at dagger.shaded.auto.common.BasicAnnotationProcessor.init(BasicAnnotationProcessor.java:118)
at org.jetbrains.kotlin.kapt3.base.incremental.IncrementalProcessor.init(incrementalProcessors.kt:33)
at org.jetbrains.kotlin.kapt3.base.ProcessorWrapper.init(annotationProcessing.kt:170)
at com.sun.tools.javac.processing.JavacProcessingEnvironment$ProcessorState.<init>(JavacProcessingEnvironment.java:508)
at com.sun.tools.javac.processing.JavacProcessingEnvironment$DiscoveredProcessors$ProcessorStateIterator.next(JavacProcessingEnvironment.java:605)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:698)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$1800(JavacProcessingEnvironment.java:91)
at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1043)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1184)
at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1170)
at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1068)
at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:78)
at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:34)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:229)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:192)
at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:100)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:108)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:118)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:93)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:526)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:90)
at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:115)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:517)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:185)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:164)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:51)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:86)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:44)
at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:98)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1549)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
e: [kapt] An exception occurred: java.lang.NoSuchFieldError: RELEASABLE_REFERENCE_MANAGER
All of build.gradle files have:
implementation "com.google.dagger:hilt-android:2.28.3-alpha"
kapt "com.google.dagger:hilt-android-compiler:2.28.3-alpha"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha02"
kapt "androidx.hilt:hilt-compiler:1.0.0-alpha02"
kapt "com.google.dagger:hilt-android-compiler:2.28.3-alpha"
implementation "javax.inject:javax.inject:1"
Root's build.gradle:
classpath "com.google.dagger:hilt-android-gradle-plugin:2.28.3-alpha"
App's build.gradle:
android {
...
defaultConfig {
...
javaCompileOptions.annotationProcessorOptions.arguments +=
["room.schemaLocation": "$projectDir/schemas".toString()]
}
MyApplication:
#HiltAndroidApp
class MyApplication : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
Timber.plant(Timber.DebugTree())
}
}
ApiModule:
#InstallIn(SingletonComponent::class) //#InstallIn(ApplicationComponent::class)
#Module
class ApiModule {
#Provides
fun products(retrofit: Retrofit): ProductsApi =
retrofit.create(ProductsApi::class.java)
}
ProductsListViewModel:
class ProductsListViewModel #ViewModelInject constructor(
private val getProductsListUseCase: GetProductsListUseCase
) : BaseViewModel() {
BaseViewModel:
open class BaseViewModel #ViewModelInject constructor() : ViewModel() {
ProductsListFragment:
import androidx.fragment.app.viewModels
//#AndroidEntryPoint
class ProductsListFragment : Fragment(R.layout.fragment_product_list) {
private val productsListViewModel: ProductsListViewModel by viewModels()
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
productsListViewModel.getProductsList() //Line 57
ProductsApi:
interface ProductsApi {
#GET("products")
fun getProducts(
#Query("page") page: Int = 1,
#Query("per_page") perPage: Int = 15
): Call<List<ProductResponse>>
}
AppModule:
#InstallIn(SingletonComponent::class) //#InstallIn(ApplicationComponent::class)
#Module
class AppModule {
#Provides
#Singleton
fun resources(application: Application): Resources = application.resources
#Provides
#Singleton
fun gson(): Gson = GsonBuilder().create()
#Provides
#Singleton
fun okHttpClient(baseHttpClient: BaseHttpClient): OkHttpClient = baseHttpClient.okHttpClient
#Provides
#Singleton
fun retrofit(baseRetrofit: BaseRetrofit): Retrofit = baseRetrofit.retrofit
}
RepositoryModule:
#InstallIn(SingletonComponent::class) //#InstallIn(ApplicationComponent::class)
#Module
class RepositoryModule {
#Suppress("PrivatePropertyName")
private val NETWORK_IO = Executors.newFixedThreadPool(5)
#Provides
fun products(productsRemoteDataSource: ProductsRemoteDataSource): ProductsRepository =
ProductsRepositoryImpl(productsRemoteDataSource, NETWORK_IO)
}
ProductsRepositoryImpl:
#Singleton
class ProductsRepositoryImpl #Inject constructor(
private val productsRemoteDataSource: ProductsRemoteDataSource,
private val networkExecutor: Executor
) : ProductsRepository {
ProductsRemoteDataSource:
#Singleton
class ProductsRemoteDataSource #Inject constructor(
private val productsApi: ProductsApi
) : BaseRemoteDataSource() {
MainActivity:
//#AndroidEntryPoint
class MainActivity : AppCompatActivity() {
Error:
2020-08-04 18:17:10.575 2047-2047/? E/LoadedApk: Unable to instantiate appComponentFactory
java.lang.ClassNotFoundException: Didn't find class "androidx.core.app.CoreComponentFactory" on path: DexPathList[[],nativeLibraryDirectories=[/system/priv-app/GoogleSdkSetup/lib/x86, /system/lib, /system/product/lib, /system/lib, /system/product/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.LoadedApk.createAppFactory(LoadedApk.java:256)
at android.app.LoadedApk.updateApplicationInfo(LoadedApk.java:370)
at android.app.ActivityThread.handleDispatchPackageBroadcast(ActivityThread.java:5951)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1941)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at com.android.server.SystemServer.run(SystemServer.java:541)
at com.android.server.SystemServer.main(SystemServer.java:349)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:908)
2020-08-04 18:17:10.582 2047-2047/? E/LoadedApk: Unable to instantiate appComponentFactory
java.lang.ClassNotFoundException: Didn't find class "androidx.core.app.CoreComponentFactory" on path: DexPathList[[],nativeLibraryDirectories=[/system/priv-app/GoogleSdkSetup/lib/x86, /system/lib, /system/product/lib, /system/lib, /system/product/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.LoadedApk.createAppFactory(LoadedApk.java:256)
at android.app.LoadedApk.updateApplicationInfo(LoadedApk.java:370)
at android.app.ActivityThread.handleDispatchPackageBroadcast(ActivityThread.java:5951)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1941)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at com.android.server.SystemServer.run(SystemServer.java:541)
at com.android.server.SystemServer.main(SystemServer.java:349)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:908)
2020-08-04 18:17:10.987 1799-2440/? E/GnssHAL_GnssInterface: gnssSvStatusCb: a: input svInfo.flags is 8
2020-08-04 18:17:10.987 1799-2440/? E/GnssHAL_GnssInterface: gnssSvStatusCb: b: input svInfo.flags is 8
2020-08-04 18:17:11.442 1817-2087/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
2020-08-04 18:17:11.442 1817-2087/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
2020-08-04 18:17:11.795 28568-28568/debug E/AndroidRuntime: FATAL EXCEPTION: main
Process: debug, PID: 28568
java.lang.RuntimeException: Cannot create an instance of class ProductsListViewModel
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:278)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:54)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:41)
at ProductsListFragment.getProductsListViewModel(Unknown Source:2)
at ProductsListFragment.setupViewModel(ProductsListFragment.kt:57)
at ProductsListFragment.onViewCreated(ProductsListFragment.kt:37)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:332)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1199)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2236)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2009)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1965)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1861)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2641)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2589)
at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2723)
at androidx.fragment.app.FragmentStateManager.activityCreated(FragmentStateManager.java:346)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1200)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1368)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1446)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1509)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2637)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2589)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1425)
at android.app.Activity.performStart(Activity.java:7825)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2020-08-04 18:17:11.795 28568-28568/debug E/AndroidRuntime: Caused by: java.lang.InstantiationException: java.lang.Class<ProductsListViewModel> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
... 42 more
2020-08-04 18:17:11.990 1799-2440/? E/GnssHAL_GnssInterface: gnssSvStatusCb: a: input svInfo.flags is 8
I had to remove all of APIs from dagger that is not hilt. I mean these:
implementation "com.google.dagger:dagger:$daggerVersion"
implementation "com.google.dagger:dagger-android-support:$daggerVersion"
kapt "com.google.dagger:dagger-android-processor:$daggerVersion"
kapt "com.google.dagger:dagger-compiler:$daggerVersion"
api "com.google.dagger:dagger-android:$daggerVersion"
api "com.google.dagger:dagger-android-support:$daggerVersion"
Then, uncomment all of #AndroidEntryPoint annotations.
(Before removing dagger APIs, if I put #AndroidEntryPoint, I was getting an error):
Did you forget to apply the Gradle Plugin?
Even with + in annotationProcessorOptions.arguments +=!
I am facing a problem while running my unit test on android studio.
If I run a unit test by right-clicking on the file and select run unit test option then unit test runs successfully, but if I use the command line option then my unit test are failing.
the command I am using ./gradlew testDebugUnitTest
the error I am getting is
Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)
java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)
at org.mockito.internal.configuration.plugins.PluginLoader$1.invoke(PluginLoader.java:74)
at com.sun.proxy.$Proxy18.isTypeMockable(Unknown Source)
at org.mockito.internal.util.MockUtil.typeMockabilityOf(MockUtil.java:29)
at org.mockito.internal.util.MockCreationValidator.validateType(MockCreationValidator.java:22)
at org.mockito.internal.creation.MockSettingsImpl.validatedSettings(MockSettingsImpl.java:240)
at org.mockito.internal.creation.MockSettingsImpl.build(MockSettingsImpl.java:228)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:61)
at org.mockito.Mockito.mock(Mockito.java:1908)
at com.walmart.rxbaggingimpl.businesslogics.AddBoxBLTest.<init>(AddBoxBLTest.kt:50)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.createTestInstance(PowerMockJUnit44RunnerDelegateImpl.java:197)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.createTest(PowerMockJUnit44RunnerDelegateImpl.java:182)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:204)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:117)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:175)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:157)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Failed to load interface org.mockito.plugins.MockMaker implementation declared in sun.misc.CompoundEnumeration#7f432e48
at org.mockito.internal.configuration.plugins.PluginInitializer.loadImpl(PluginInitializer.java:54)
at org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:57)
at org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:44)
at org.mockito.internal.configuration.plugins.PluginRegistry.<init>(PluginRegistry.java:22)
at org.mockito.internal.configuration.plugins.Plugins.<clinit>(Plugins.java:19)
at org.mockito.internal.util.MockUtil.<clinit>(MockUtil.java:24)
... 51 more
Caused by: java.lang.ClassCastException: class com.sun.tools.javac.api.JavacTool
at java.lang.Class.asSubclass(Class.java:3404)
at javax.tools.ToolProvider.getSystemToolClass(ToolProvider.java:178)
at javax.tools.ToolProvider.getSystemTool(ToolProvider.java:158)
at javax.tools.ToolProvider.getSystemJavaCompiler(ToolProvider.java:102)
at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.<init>(InlineByteBuddyMockMaker.java:170)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at org.mockito.internal.configuration.plugins.PluginInitializer.loadImpl(PluginInitializer.java:49)
... 56 more
code is
class MYTest: BaseTest() {
private val api = APISERVICE(APIServiceClientMock)
private val logapiServices = LogServices(APIServiceClientMock)
private val myBL= MYBL(api, logspiServices, MockEventTrackLogger)
fun getMockResponse(): StopViewResponse {
val expectedResponse = StopViewResponse()
expectedResponse.responseCode = Constants.SUCCESS_CODE
expectedResponse.responseTexts = listOf("Success")
expectedResponse setMockResponseAs SUCCESS
return expectedResponse
}
#Test
fun test1() {
runBlocking {
val data = MyModel()
data.id = 1
data.orderId = 1
getMockResponse()
rxPackBL.completeView(data)
Assert.assertTrue(myBL.getCompleteEvent().value?.peekContent() is Success<*>)
Utils.data= data
myBL.completeView()
Assert.assertTrue(myBL.getCompleteEvent().value?.peekContent() is Success<*>)
}
}
Any help will be appreciated
Thanks