在主要活动上,当按下按钮时,服务和另一个活动正在启动:
public class MainActivity extends Activity { public void onButtonClicked() { startActivity(SecondActivity.getStartIntent()); startService(MyIntentService.getStartIntent()); } }
我正在测试是否正在启动预期的组件:
public class MainActivityTest { @Rule public final IntentsTestRule<MainActivity> intentsRule = new IntentsTestRule<>(MainActivity.class,true); @Test public void shouldStartServiceOnButtonClicked() { onView(withId(R.id.button)).perform(click()); intended(hasComponent(hasClassName(SecondActivity.class.getName()))); intended(hasComponent(hasClassName(MyIntentService.class.getName()))); } }
但是我收到了错误:
Caused by: junit.framework.AssertionFailedError: Wanted to match 1 intents. Actually matched 0 intents. IntentMatcher: has component: has component with: class name: is "com.example.MyIntentService" package name: an instance of java.lang.String short class name: an instance of java.lang.String Matched intents:[] Recorded intents: -Intent { cmp=com.example/.SecondActivity (has extras) } handling packages:[[com.example]],extras:[Bundle[...]]) at junit.framework.Assert.fail(Assert.java:50)
注册SecondActivity的开始.为什么我的IntentService的启动没有注册(我检查它是否已启动)?
解决方法
我在源代码中挖掘,因为我正在尝试做类似的事情,这就是我发现的:
‘预期’匹配器通过查看记录的意图列表来工作.这些是由调用Intents.init()时在IntentMonitor实例中注册的回调跟踪的. IntentMonitor实例由当前的Instrumentation定义.每次调用IntentMonitor的signalIntent()时,都会触发Intents中的回调.
问题在于,在您使用intent调用activity.startService()的情况下,signalIntent()实际上永远不会被调用.这是因为AndroidJunitRunner情况下的signalIntent()只能被ExposedInstrumentationApi上暴露的方法调用(这恰好与各种startActivity()方法相关).为了使用带有startService()的espresso-intents,似乎需要一个startService()的检测钩子,它允许在IntentMonitor上调用signalIntent().
我没有将自定义Instrumentation添加到我的测试apks的经验,但这将是我的下一个调查途径.如果我发现任何有用的东西,我会更新我的答案.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。