【发布时间】:2019-04-12 12:33:33
【问题描述】:
“未解决的参考:配对”使用 Kotlin 和 Robolectric
我尝试将 Robolectric 添加到使用 android.util.Pair 的项目中,这样我就可以对关联的类进行单元测试。该项目是用 java 编写的,但单元测试(到目前为止)都是用 Kotlin 编写的。
当我尝试运行单元测试时,我得到了错误:
:app:createMockableJar UP-TO-DATE
e: E:\...\TestK.kt: (3, 21): Unresolved reference: Pair
e: E:\...\TestK.kt: (12, 17): Unresolved reference: Pair
:app:compileDebugUnitTestKotlin FAILED
我创建了一个简单的测试用例:
import android.util.Pair
import org.junit.Assert.assertEquals
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class TestK {
@org.junit.Test
fun testk() {
val p = Pair.create("Foo", "Bar")
assertEquals("Foo", p.first)
assertEquals("Bar", p.second)
}
}
这会产生错误,但如果我在 java 中创建相同的测试,它可以正常工作:
import android.util.Pair;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import static org.junit.Assert.assertEquals;
@RunWith(RobolectricTestRunner.class)
public class Test
{
@org.junit.Test
public void test()
{
Pair<String, String> p = Pair.create("Foo", "Bar");
assertEquals("Foo", p.first);
assertEquals("Bar", p.second);
}
}
知道可能出了什么问题吗?
我的 gradle 文件有以下 deps:
apply plugin: 'com.android.application'
apply plugin: "kotlin-android"
... stuff ...
testImplementation 'junit:junit:4.12'
testImplementation "org.robolectric:robolectric:4.0.1"
我正在使用 Kotlin 1.3
【问题讨论】:
-
你不能在 Kotlin 中使用 Java Pair。
-
为什么不呢?我以为你可以使用 Java 中的任何东西。我正在尝试测试的真实 (java) 代码具有返回
Pair<>的函数。 -
你的代码能否解析这一行:
import android.util.Pair;? -
@Aaron 在 Java 中可以,但在 Kotlin 中不行,这就是我想要弄清楚的。 Robolectric 应该提供此类 afaik。
-
我可能是错的,但这可能与您的测试 gradle 有关,您有
apply plugin: 'com.android.library'或apply plugin: 'kotlin-android'吗?
标签: android kotlin robolectric