我试图在我目前的android项目中编写简单的集成测试,该项目完全用Kotlin编写.

The problem is that the test doesn't even start and fails with the following error:

Error:(4, 36) Unresolved reference: testing
Error:(18, 52) Unresolved reference: InstantTaskExecutorRule
Error:Execution failed for task ':app:kaptGenerateStubsDebugAndroidTestKotlin'.
> Compilation error. See log for more details

我试着用谷歌搜索这个问题,但没有成功.

我已经try 了以下步骤:

  1. 判断是否安装了包含InstantTaskExecutorRule的库,我可以查看此软件包(是的,我可以)
  2. 判断我的测试是否放在正确的文件夹中(是的,它在androidTest中)
  3. 判断我是否正确启动了测试(可能是通过右键单击Package pkgName (androidTest),然后"Run test in."来启动它们)

I've also tried to rename my source dirs to koltin from java, and set proper values to sourceSets but changed it back because of no success as well and considered it's not a reason.

Important notice:

If I comment the line import android.arch.core.executor.testing.InstantTaskExecutorRule and all code, related to InstantTaskExecutorRule (meaning that the whole test logic will be empty) and place a simple assert for example, then everything works just fine.

但我想用这个特殊的InstantTaskExecutorRule,想知道问题到底是什么,以及如何解决它,或者至少想知道我应该在哪里寻找什么.

Here is my test code:

import android.arch.core.executor.testing.InstantTaskExecutorRule
import android.arch.persistence.room.Room
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4

import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import com.myapp.storage.base.AppDataBase


@RunWith(AndroidJUnit4::class)
class UserDaoTest{
    @JvmField @Rule val instantTaskExecutorRule = InstantTaskExecutorRule()

    private lateinit var db: AppDataBase

    @Before
    @Throws(Exception::class)
    fun setUp(){
        db = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(), AppDataBase::class.java)
                .allowMainThreadQueries()
                .build()
    }

    @After
    fun closeDB(){
        db.close()
    }

    @Test
    fun getUsersWhenNoUserInserted(){
        db.userDao().allUsers()
                .test().assertNoValues()
    }

}

推荐答案

根据官方的google documentation,我们应该以这样的方式添加架构组件(LiveData)的测试助手:

// Test helpers for LiveData
testImplementation "android.arch.core:core-testing:1.1.0"

And at least for me it just doesn't work. (see the question above)

How it should be actually:

// Test helpers for LiveData
androidTestImplementation "android.arch.core:core-testing:1.1.0"

现在一切都很好!

Kotlin相关问答推荐

如何在Jetpack Compose中的列中渲染图像

如何在使用Kotlin Coroutines时检测和记录何时出现背压

Gradle Jooq配置自定义生成器

如何接受任何派生类KClass

将一个列表元素分组为多个组(indexBy)

第二个协程永远不会执行

测试协程和线程之间的差异,我在kotlin中使用线程时无法得到OOM错误

Kotlin 中列表或数组的乘积

有没有办法重用 Job 实例?

为什么 IntelliJ Idea 无法识别我的 Spek 测试?

比较 Kotlin 中的可比对象列表

Kotlin boxed Int 不一样

未在IntelliJ IDEA上运行临时文件

在kotlin中,如何模拟封装回调函数?

如何将命令行参数传递给Gradle Kotlin DSL

我们如何在Java注释声明中引用Kotlin常量?

Kotlin 中更好的回调方法是什么?侦听器与高阶函数

如何在Kotlin中使方法param可变?

Kotlin 与 C# 中的标志枚举变量具有相似效果的方式是什么

Kotlin flatMap - map