Kam*_*ryn 6 android android-intent intentservice android-espresso
我正在尝试使用Espresso-2.2测试我的应用行为
在主要活动上,当按下按钮时,服务和另一个活动正在启动:
public class MainActivity extends Activity {
public void onButtonClicked() {
startActivity(SecondActivity.getStartIntent());
startService(MyIntentService.getStartIntent());
}
}
Run Code Online (Sandbox Code Playgroud)
我正在测试是否正在启动预期的组件:
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())));
}
}
Run Code Online (Sandbox Code Playgroud)
但是我收到了错误:
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)
Run Code Online (Sandbox Code Playgroud)
注册SecondActivity的开始.为什么我的IntentService的启动没有注册(我检查它是否已启动)?
jdo*_*yer 12
tl; dr看起来好像这是可能的,因为当前的espresso-intents提供了功能
我在源代码中挖掘,因为我正在尝试做类似的事情,这就是我发现的:
'预期'匹配器通过查看记录的意图列表来工作.这些是由调用Intents.init()时在IntentMonitor实例中注册的回调跟踪的.IntentMonitor实例由当前的Instrumentation定义.每次调用IntentMonitor的signalIntent()时,都会触发Intents中的回调.
问题在于,在您使用intent调用activity.startService()的情况下,signalIntent()实际上永远不会被调用.这是因为AndroidJunitRunner情况下的signalIntent()只能被ExposedInstrumentationApi上暴露的方法调用(这恰好与各种startActivity()方法相关).为了使用带有startService()的espresso-intents,似乎需要一个startService()的检测钩子,它允许在IntentMonitor上调用signalIntent().
我没有将自定义Instrumentation添加到我的测试apks的经验,但这将是我的下一个调查途径.如果我发现任何有用的东西,我会更新我的答案.
我可以做出有根据的猜测,问题在于您试图断言 是IntentService在调用后立即创建并运行的startService(),而实际上startService()不是同步调用。它确实发生在 UI 线程上,但不是立即发生。您可以将验证推迟几个磨坊,然后检查服务是否已启动。
| 归档时间: |
|
| 查看次数: |
1145 次 |
| 最近记录: |