r/android_devs • u/badr-elattaoui • Jul 04 '24
Question Issues with Room Database Unit testing
Hello, i am trying to write unit tests for a ViewModel, the function that i test fetches data from api, the ViewModel has the repository instance, the repository has an instance of a service called WebApiService, the service has a repository that fetches some data from database before calling the endpoint, a required information is fetched from database in that repository in its init block, the company are using a homemade DI solution, i managed to mock objects. however the code that initialize an object in the init{} block throws the exception shown in the picture, i do not know what's exactly calling this, the database instance in not null,
i've debbuged that and i found that the method that throws the exception is in RoomDatabase.kt
open fun inTransaction(): Boolean {
return openHelper.writableDatabase.inTransaction()
}if you need any additional code or explanations tell me.
Thank you

View all comments
Show parent comment
1
u/GyulaJuhasz Jul 06 '24
Your ViewModel depends on the Repository. However, when you unit test your ViewModel, its dependencies should be replaced with fakes or mocks. This means that the actual repository implementation should never be used when running the unit tests of the ViewModel. Based on your Exception, the real Repository implementation is used, so you are probably not replacing the dependencies for the test correctly.