As I was running a test for a ViewModel function, I encountered the following error:
[...] Main Thread @coroutine java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
I think it may be caused by the viewModelScope
from viewModelScope.launch {}
being used by the running test, which may not be accessible during unit tests.
What I did to fix this error on my unit test was to enable main thread operations in my in-memory Room database test instance. I simply added .allowMainThreadQueries()
while building the database instance like so:
1 2 3 4 |
db = Room.inMemoryDatabaseBuilder( context, MyRoomDatabase::class.java) .allowMainThreadQueries() .build() |
Is that the best way to do it? If you got a better suggestion, please comment! I’d love to hear about it.