android - 如何使用 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。
概括
有人知道我在做什么错吗?我找不到将所有这些联系在一起并为此意图创建匹配器的方法。任何帮助将不胜感激!
解决方案
如果您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);
推荐阅读
- kotlin - 如何使用 mockk 调用 lambda 回调
- office-js - 移动设备上的 Outlook 加载项
- javascript - Cordova-keyboard 在 iOS 上不起作用并在键盘上方显示一个黑暗区域
- php - 将mysql中的所有表数据打印到html表中
- javascript - 按名称和数组搜索
- c# - 没有服务定位器的多个实例的依赖注入
- css - Ionic4 背景图像
- javascript - switch case语句react-redux上的语法错误
- azure - Azure 计时器功能未运行
- html - 从 Internet Explorer 的下拉列表中选择时,如何使用 FireEvent“Onchange”触发网页更新?