我尝试了此测试,但getHits()始终返回0。有人可以帮助我吗?
public void testSettingsAboutShazamClickOnLink() {
Instrumentation inst = getInstrumentation();
IntentFilter intentFilter = new IntentFilter(android.content.Intent.ACTION_SENDTO);
intentFilter.addDataScheme("mailto");
ActivityMonitor monitor = inst.addMonitor(intentFilter, null, false);
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
assertEquals(0, monitor.getHits());
inst.getContext().startActivity(emailIntent);
monitor.waitForActivityWithTimeout(5000);
assertEquals(1, monitor.getHits());
inst.removeMonitor(monitor);
}
最佳答案
我解决了这个问题。我使用了Robotium的Solo,显然Solo插入了一个与每个Filter匹配的ActivityMonitor,因此,当您调用startActivity时,它将在Instrumentation类中调用execStartActivity,其代码为
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
if (mActivityMonitors != null) {
synchronized (mSync) {
final int N = mActivityMonitors.size();
for (int i=0; i<N; i++) {
final ActivityMonitor am = mActivityMonitors.get(i);
if (am.match(who, null, intent)) {
am.mHits++;
if (am.isBlocking()) {
return requestCode >= 0 ? am.getResult() : null;
}
break;
}
}
}
}
一旦有一个ActivityMonitor与之匹配,该监视器的mHits就会增加,“中断周期”结束。鉴于调用Solo是我做的第一件事,因此要检查的第一个ActivityMonitor是Solo,因为它匹配所有内容,因此不检查之后添加的任何其他ActivityMonitors,因此其他监视器不会增加mHits变量。如果您想了解更多信息,请参见Instrumentation类的execStartMonitor方法,请记住在调用startActivity之后将调用此方法。
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/android/app/Instrumentation.java#Instrumentation.execStartActivity%28android.content.Context%2Candroid.os.IBinder%2Candroid.os.IBinder%2Candroid.app.Activity%2Candroid.content.Intent%2Cint%29