首页 > 解决方案 > 如何使用 Espresso 存根 Intent.createChooser Intent

问题描述

问题

我的应用程序中有一个图像,并且正在将其共享给任何其他可以处理图像共享的应用程序,并且该功能可以正常工作。

我正在编写 Espresso UI 测试来拦截意图并确保它具有正确的操作和附加功能,但似乎无法使其正常工作。

代码

这是创建意图时的代码:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType(MediaType.PNG.toString());
startActivity(Intent.createChooser(intent, "send");

这是我在测试中匹配 Intent 的尝试,但找不到匹配项:

Intents.init();
launchActivity(MyFragment.newIntent(getTargetContext());

Matcher<Intent> expectedIntent = allOf(
    hasAction(Intent.ACTION_CHOOSER),
    hasExtra(
        Intent.ACTION_SEND,
        hasExtra(Intent.EXTRA_STREAM, EXPECTED_SHARE_URI) // Expected URI has been copied from the extras 'uriString' value when debugging
    )
);
intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null));
MyScreen.clickShareButton(); // performs click on the share button
intended(expectedIntent);
Intents.release();

错误

IntentMatcher: (has action: is "android.intent.action.CHOOSER" and has extras: has bundle with: key: is "android.intent.extra.STREAM" value: is "[my uri appears here]")

附加信息

调试时,创建的意图会产生一个带有动作“android.intent.action.CHOOSER”的意​​图,并且有一个额外的 Intent 类型,带有动作“android.intent.action.SEND”和类型“image/png” ,然后有一个额外的 HierarchicalUri 和 uriString。

概括

有人知道我在做什么错吗?我找不到将所有这些联系在一起并为此意图创建匹配器的方法。任何帮助将不胜感激!

标签: androidandroid-intentandroid-espresso

解决方案


如果您intended(expectedIntent)因为意图不匹配而在此行收到错误,则可能是因为Intent.createChooser将您的意图作为带有 key 的额外数据Intent.EXTRA_INTENT。在您的情况下,您只需要为选择器添加一个额外的意图匹配器:

Matcher<Intent> intent = allOf(
    hasAction(Intent.ACTION_SEND),
    hasExtra(Intent.EXTRA_STREAM, EXPECTED_SHARE_URI)
);

Matcher<Intent> expectedIntent = allOf(
    hasAction(Intent.ACTION_CHOOSER),
    // Intent.createChooser put your intent with the key EXTRA_INTENT
    hasExtra(Intent.EXTRA_INTENT, intent)
);

intending(anyIntent()).respondWith(new Instrumentation.ActivityResult(0, null));

MyScreen.clickShareButton();

intended(expectedIntent);

推荐阅读