我想测试点击按钮时是否启动了第二个活动
public void testLanguaeSelect() {
startActivity(activityLanguageIntent, null, null);
TextView textViewTitleBarText = (TextView) getActivity().findViewById(R.id.titleBarText);
assertEquals(textViewTitleBarText.getText(), "Sprache");
final TextView textViewTextMiddle = (TextView) getActivity().findViewById(R.id.listItemTextMiddle);
assertEquals(textViewTextMiddle.getText(), "Deutsch");
((RelativeLayout) textViewTextMiddle.getParent()).performClick();
// check if intend is sent
Intent startedActivityIntent = getStartedActivityIntent();
assertNotNull(startedActivityIntent);
// wait for mainactivity to be started
ActivityMonitor mainActivityMonitor = new Instrumentation.ActivityMonitor(MainActivity.class.getName(), null, false);
getInstrumentation().addMonitor(mainActivityMonitor);
Activity activity = mainActivityMonitor.waitForActivityWithTimeout(10000);
assertNotNull("Activity was not started", activity);
}
onlclick功能
@Override
public void onClick(View v) {
v.startAnimation(AnimationUtils.loadAnimation(v.getContext(), R.layout.animation_item_click));
Intent intent = new Intent(v.getContext(), MainActivity.class);
intent.putExtra("language", locale);
v.getContext().startActivity(intent);
}
Intend是正确的并且调用了onclick函数,但waitForMonitorWithTimeout总是在超时运行并返回null。
我的Android版本
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="21" />
答案 0 :(得分:0)
MainActivity secondActivity = (MainActivity) getInstrumentation().waitForMonitorWithTimeout(monitor, 3);
上述答案方法中提到的参数3以毫秒为单位,而不是以秒为单位。因此,如果它是3,有时测试用例会失败因为在5毫秒内它无法加载下一个活动。所以5000或10000毫秒肯定会更好。在文档中,他们在几秒钟内给出了它但事实上它是以毫秒为单位。所以下面的方法比上面的方法更好用
MainActivity secondActivity = (MainActivity) getInstrumentation().waitForMonitorWithTimeout(monitor,10000);
参考: test if a button starts a new activity in android junit (pref without robotium)?