如何在 Android Espresso 测试中测试 setResult()?

How can I test setResult() in an Android Espresso test?

在Android Espresso 测试中,有什么好的方法可以测试结果代码和数据吗?我正在使用 Espresso 2.0。

假设我有一个名为 BarActivity.classActivity,它在执行某些操作时调用 setResult(int resultCode, Intent data) 并使用适当的负载。

我想写一个测试用例来验证resultCodedata。但是,因为 setResult() 是一个 final 方法,所以我无法覆盖它。

我想到的一些选项是:

尝试考虑两害相权取其轻,或者是否有关于如何对此进行测试的任何其他建议。有什么建议么?谢谢!

如果你愿意升级到2.1,那就看看Espresso-Intents:

Using the intending API (cousin of Mockito.when), you can provide a response for activities that are launched with startActivityForResult

这基本上意味着可以在启动特定 activity 时构建和 return 任何结果(在您的情况下 BarActivity class)。

在此处查看此示例:https://google.github.io/android-testing-support-library/docs/espresso/intents/index.html#intent-stubbing

还有 my answer 有点类似的问题(但使用联系人选择器 activity),其中我展示了如何构建结果并将其发送回 Activity调用了 startActivityForResult()

如果同时切换到最新的 Espresso 版本 3.0.1,您可以简单地使用 ActivityTestRule 并获得如下 Activity 结果:

assertThat(rule.getActivityResult(), hasResultCode(Activity.RESULT_OK));
assertThat(rule.getActivityResult(), hasResultData(IntentMatchers.hasExtraWithKey(PickActivity.EXTRA_PICKED_NUMBER)));

您可以找到一个工作示例 here

这对我有用:


@Test
    fun testActivityForResult(){

        // Build the result to return when the activity is launched.
        val resultData = Intent()
        resultData.putExtra(KEY_VALUE_TO_RETURN, true)

        // Set up result stubbing when an intent sent to <ActivityB> is seen.
        intending(hasComponent("com.xxx.xxxty.ActivityB")) //Path of <ActivityB>
            .respondWith(
                Instrumentation.ActivityResult(
                    RESULT_OK,
                    resultData
                )
            )

        // User action that results in "ActivityB" activity being launched.
        onView(withId(R.id.view_id))
            .perform(click())

      // Assert that the data we set up above is shown.
     onView(withId(R.id.another_view_id)).check(matches(matches(isDisplayed())))
    }

假设在 onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)

上进行如下验证

if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {

    data?.getBooleanExtra(KEY_VALUE_TO_RETURN, false)?.let {showView ->
                if (showView) {
                 another_view_id.visibility = View.VISIBLE
                }else{
                 another_view_id.visibility = View.GONE
                 }
            }
        }

我按照本指南作为参考:https://developer.android.com/training/testing/espresso/intents and also i had to check this links at the end of the above link https://github.com/android/testing-samples/tree/master/ui/espresso/IntentsBasicSamplehttps://github.com/android/testing-samples/tree/master/ui/espresso/IntentsAdvancedSample