未解决的参考:TestCoroutineDispatcher

Unresolved reference: TestCoroutineDispatcher

我正在尝试在 TestCoroutineDispatchers 和 runBlockingTest 的帮助下测试房间数据库插入和获取。因为我需要创建数据库实例的上下文,所以我尝试在 androidTest 中实现测试,但出现以下错误。谁能帮我解决一下。

我按照此 link 中的说明进行操作 https://medium.com/@eyalg/testing-androidx-room-kotlin-coroutines-2d1faa3e674f

“未解决的参考:TestCoroutineDispatcher” “未解决的参考:TestCoroutineScope” “未解决的参考:runBlockingTest”

@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
class PokemonDatabaseTest {

    private lateinit var pokemonDao : PokemonFavouriteDao
    private lateinit var db : PokemonDatabase


    val testDispatcher = TestCoroutineDispatcher()
    val testScope = TestCoroutineScope(testDispatcher)


    @Before
    fun setUp() {

      db = Room
          .inMemoryDatabaseBuilder(InstrumentationRegistry.getInstrumentation().context, PokemonDatabase::class.java)
          .setTransactionExecutor(testDispatcher.asExecutor())
          .setQueryExecutor(testDispatcher.asExecutor()).build()
        pokemonDao = db.pfDao
    }

    @Test
    fun storeFavouritePokemon()   = runBlockingTest {
        val pokemon = DataFactory.makePokemon()
        assertThat(pokemonDao.getFavouritePokemon(), null)
    }
}

我正在使用以下依赖项:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.2'

androidTestImplementation 'androidx.test:runner:1.1.0'
androidTestImplementation 'androidx.test:rules:1.1.0'
testImplementation 'androidx.test:core:1.2.0'
testImplementation "org.robolectric:robolectric:4.0.2"

def archCoreVersion = '2.1.0'
    def espressoCoreVersion = "3.3.0"
    def espressoVersion = '3.3.0'

espressoCore: "androidx.test.espresso:espresso-core:$espressoCoreVersion",
        espressoContrib : "androidx.test.espresso:espresso-contrib:$espressoVersion",
        espressoIntents : "androidx.test.espresso:espresso-intents:$espressoVersion",
        espressoResource: "androidx.test.espresso:espresso-idling-resource:$espressoVersion",
        coreRuntime : "androidx.arch.core:core-runtime:$archCoreVersion",
        coreTesting : "androidx.arch.core:core-testing:$archCoreVersion"

您为单元测试声明了 testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.2'

但是如果你想为 androidTest 使用 TestCoroutineDispatcher 你还必须声明它的依赖关系:androidTestImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.2'.

对于您想用于 androidTest 的其他依赖项也是如此。