使用泛型为 class 创建 Espresso 匹配器

Creating an Espresso Matcher for a class with generics

我正在尝试为 espresso 创建一个新的 Matcher,以便能够 select 一个列表项。这适用于像 Office 这样的简单 class。请参阅此示例。

  private fun withOffice(title: String): Matcher<Any> {
    return object : BoundedMatcher<Any, Office>(Office::class.java) {
        override fun describeTo(description: Description?) {
            description?.appendText("with title '$title'");
        }

        public override fun matchesSafely(office: Office): Boolean {
            return office.name == title
        }
    }
}

然而,在引入泛型时事情变得更加困难,例如 class。

class KeyTranslationPair<F, S> extends Pair<F, S>

正在尝试创建这样的匹配器

  private fun withCompanyType(companyType: CompanyType): Matcher<Any> {
    return object : BoundedMatcher<Any, KeyTranslationPair<CompanyType, String>>(KeyTranslationPair<CompanyType, String>::class.java) {
        override fun describeTo(description: Description?) {
            description?.appendText("with companyType '$companyType'");
        }

        public override fun matchesSafely(keyTranslationPair: KeyTranslationPair<CompanyType, String>): Boolean {
            return keyTranslationPair.key == companyType
        }
    }
}

导致以下错误

我的假设是 kotlin 与 java 类型系统混淆了。 也许这里有人有想法。

那是因为 KeyTranslationPair<CompanyType,Strnig> 不是 class,当说 class 表示 KeyTranslationPair::class.java 时,您可以这样做:

return object : BoundedMatcher<Any, KeyTranslationPair<*,*>>(KeyTranslationPair::class.java)

你是说你不知道 KeyTranslationPair 里面有什么,因为它是 Generic 你必须把 matchesSafely 改成 :

override fun matchesSafely(item: KeyTranslationPair<*, *>?): Boolean {
   return item?.key == companyType
}

您还可以检查 Key 是否是 CompanyType 的实例:

override fun matchesSafely(item: KeyTranslationPair<*, *>?): Boolean {
    if(item?.key is CompanyType){
        return item.key == companyType
    }
        return false
    }

希望对您有所帮助。