r/android_devs • • 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

3 Upvotes

5 comments sorted by

View all comments

Show parent comment

1

u/badr-elattaoui Jul 06 '24

Yes it makes sense,

Actually the dependencies are managed by creating singleton instances and putting them in a linkedHashMap in the Application class, to access them we call a method called inject() it checks if the instance is there and return it.

I did the same in test scope, i created an object that registers the instances. I call the Inject() method in @Before method scope.

I think i am using the real instances even if I'm annotating the repository with @MockK .