【问题标题】:Using Espresso to stub Intents started during the onCreate of the tested activity使用 Espresso 对在测试活动的 onCreate 期间启动的 Intent 进行存根
【发布时间】:2017-03-19 15:18:07
【问题描述】:

我正在测试一个在其onCreate() 期间启动另一个活动的活动。第二个活动以startActivityForResult() 开始,然后主要活动等待onActivityResult()

我正在尝试使用 Espresso 进行测试,尝试使用 intending() 存根第二个活动,并使用 intended() 验证它是否发生。

尽管 espresso-intents 似乎并非设计为与从 onCreate() 方法 (see the warning in the last paragraphs here) 中启动的意图一起使用。

有没有人设法存根从 onCreate() 开始的 Intent,如果是,怎么做?

【问题讨论】:

    标签: java android testing android-activity android-espresso


    【解决方案1】:

    通过使用以下 Kotlin 代码,我能够为自己工作:

    @Rule @JvmField
    val activityRule: IntentsTestRule<MainActivity> =
            object : IntentsTestRule<MainActivity>(MainActivity::class.java, true, false) {
                override fun beforeActivityLaunched() {
                    super.beforeActivityLaunched()
                    Intents.init()
                    intending(hasComponent(LaunchedFromOnCreateActivity::class.java.name)).respondWith(Instrumentation.ActivityResult(RESULT_OK, null))
                }
                override fun afterActivityLaunched() {
                    Intents.release()
                    super.afterActivityLaunched()
                }
            }
    

    一般的想法是,由于生命周期的东西发生在 beforeActivityLaunched 和 afterActivityLaunched 之间,你需要在那里设置你的意图。也就是说,这无法进行预期测试。

    【讨论】:

    • 虽然这不是我所希望的(真的希望能够进行预期的测试),但它在技术上确实回答了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    相关资源
    最近更新 更多