I have implemented a ContentProvider that uses a Room database to store the data. The implementation is done in kotlin and it follows the same pattern shown in this Google example. The ContentProvider works fine when used in an app. Now I want to write some tests and I am relying on ProviderTestRule for doing so. The configuration I have seems fine, but unfortunately I am getting the following exception, which looks like some initialisation is missing and then the context is not available.
java.lang.UnsupportedOperationException
at androidx.test.rule.provider.DelegatingContext.getSystemService(DelegatingContext.java:277)
at androidx.room.RoomDatabase$JournalMode.resolve(RoomDatabase.java:517)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:943)
I wasn't able to find any example of how to test this scenario. Any hint would be really helpful!
ProviderTestRule
internally usesDelegatingContext
, which is a wrapper around the application context that purposely limits its capabilities.From the source code you can see that
context.getSystemService
is stubbed out, throwingUnsupportedOperationException
most of the time:I have no clear explaination why they forbid access to system services for
ProviderTestRule
in the first place. Unfortunately, it seems that Room requires access to theActivityManager
in order to find the most appropriateJournalMode
.What you can try to workaround the situation:
JournalMode
of you Room database toJournalMode.WRITE_AHEAD_LOGGING
(orJournalMode.TRUNCATE
), orProviderTestRule
that uses the real application context to and allow access to the desired system service.