【问题标题】:"Unresolved reference: Pair" using Kotlin with Robolectric“未解决的参考:配对”使用 Kotlin 和 Robolectric
【发布时间】: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&lt;&gt; 的函数。
  • 你的代码能否解析这一行:import android.util.Pair;?
  • @Aaron 在 Java 中可以,但在 Kotlin 中不行,这就是我想要弄清楚的。 Robolectric 应该提供此类 afaik。
  • 我可能是错的,但这可能与您的测试 gradle 有关,您有 apply plugin: 'com.android.library'apply plugin: 'kotlin-android' 吗?

标签: android kotlin robolectric


【解决方案1】:

事实证明,我的项目中有一个空的Pair.java 文件android.util。这是我最初为 Pair 创建一个 java 存根的地方,当切换到 Robolectric 时,我将文件中的所有内容都注释掉了。

虽然这对于 java 来说似乎很好,但对于 Kotlin 来说显然还不够,我猜它仍在尝试使用该文件?无论如何,在我删除空文件后,一切都开始正确编译!

【讨论】:

    【解决方案2】:

    在 Kotlin 中,我们使用 UtilPair 代替 Pair

    只需要导入

        android.util.Pair as UtilPair
    

    然后把它当作

       val myPair = UtilPair.create<String?, String?>("Foo", "Bar")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2018-10-16
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多