【问题标题】:Type inference failed: Not enough information to infer parameter T in fun <T : Context!> getApplicationContext(): T! Please specify it explicitly类型推断失败:没有足够的信息来推断 fun <T : Context!> getApplicationContext(): T! 中的参数 T请明确指定
【发布时间】:2020-04-03 20:54:30
【问题描述】:

我正在尝试为我的 android 应用程序编写一些测试,这对我来说真的很麻烦。许多障碍之一就是这个错误

Type inference failed: Not enough information to infer parameter T in fun <T : Context!> getApplicationContext(): T! Please specify it explicitly.

发生在这一行

val actualIntent: Intent = shadowOf(ApplicationProvider.getApplicationContext())
            .nextStartedActivity

完整的测试代码如下所示

@Test
fun clickingLogin_shouldStartLoginActivity() {
    val scenario = launch(LogInActivity::class.java)

    scenario.onActivity { activity ->
        activity.go_to_register_button.performClick()
        val expectedIntent = Intent(activity, RegistrationActivity::class.java)
        val actual: Intent = shadowOf(ApplicationProvider.getApplicationContext())
            .nextStartedActivity

        expectedIntent.component shouldBeEqualTo actual.component
    }
}

基本上 shadowOf 函数是重载的,可以返回很多想法,我需要指定类型。

我认为它应该类似于shadowOf&lt;SomeType&gt;(...) 但我不知道实际的类型应该是什么。

任何帮助将不胜感激。

编辑 我正在关注 roboloctric guideline 但试图以 androidX 方式编写它

【问题讨论】:

    标签: android unit-testing kotlin compiler-errors robolectric


    【解决方案1】:

    IntentObject 的不同类型,它不扩展自 Context

    这一行:

    val actualIntent: Intent = shadowOf(ApplicationProvider.getApplicationContext())

    提供Context 作为参数,并返回ShadowContext,而不是Intent

    文档参考:http://robolectric.org/javadoc/3.0/org/robolectric/Shadows.html#shadowOf-android.content.Context-

    基本上它告诉你一棵树不能是一种汽车。

    【讨论】:

    • 但该行以 .nextStartedActivity 继续
    • 您可以在之后输入任何内容,而且结果都是一样的——这纯粹是一个继承问题。
    【解决方案2】:

    我可能没有问得清楚。但是对于在这里遇到同样问题的任何人来说,这里是一个解决方案。

    我不知道如何在正常测试中测试活动是否产生正确的意图。但在仪器测试中,它是这样的:

    @get:Rule
    var activityRule: IntentsTestRule<MyActivity> =
            IntentsTestRule(MyActivity::class.java)
    
    @Test
    fun testIntent () {
    
      // perform some actions
      // than verify
      intended(hasComponent(OtherActicity::class.qualifiedName))
      intended(hasExtra(A_CONSTANT, someValue))
    }
    
    

    你需要一个依赖才能工作

    androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.0'

    more info here

    【讨论】:

      猜你喜欢
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 2020-03-31
      • 1970-01-01
      相关资源
      最近更新 更多