You may want to use context
in your unit test in jetpack. But if you do nothing you may get error some kinds of context
.
Hey, how do I use context
in the unit test?
There is an easy way to use it. This is Robolectric.
You have to solve dependency about Robolectric in the module level build.gradle.kt
.
(I use version catalogs
for the version management.)
testImplementation(libs.robolectric)
Next, you prepare the DispatcherRule
for validating test modules. The following code is just a minimum example.
@OptIn(ExperimentalCoroutinesApi::class)
class MainDispatcherRule(
private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(),
) : TestWatcher() {
override fun starting(description: Description) {
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: Description) {
Dispatchers.resetMain()
}
}
Finally, put the annotaion on your test class.
@RunWith(RobolectricTestRunner::class)
class SomeTest {
// continue the test code...
コメント