joe*_*cks 3 testing android android-espresso android-instrumentation
使用Espresso,我尝试使用Home按钮测试将活动发送到后台,然后再次将其放到前台进行一些检查:
@EspressoTest
public void test() {
onSomeView().check(matches(isDisplayed()));
getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_HOME);
Context context = getInstrumentation().getTargetContext();
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
onSomeView().check(matches(isDisplayed()));
}
Run Code Online (Sandbox Code Playgroud)
我不得不使用intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
异常建议的,但除此之外我还测试了,启动它作为Launcher Activity,或使用
FLAG_ACTIVITY_REORDER_TO_FRONT
,但视图不可见.即使测试通过.
好吧我明白了.首先,有必要使用getActivity提供的Activity Context,然后我可以使用Intents在后台和前台发送活动,使用HOME类和FLAG_ACTIVITY_REORDER_TO_FRONT:
private void goHome(Activity activity) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
activity.startActivity(intent);
}
private void bringToForeground(Activity activity) {
Intent intent = new Intent(activity, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
activity.startActivity(intent);
}
@EspressoTest
public void test() {
//do some ui stuff to ensure the activity is up and running
goHome(getActivity());
// eventually sleep, or implement an idling resource
bringToForeground(getActivity());
// do some ui tests
}
Run Code Online (Sandbox Code Playgroud)
如果您要转到BackgroundByClickingHomeThenGetBackToTheApp,请考虑此响应,因为它可以100%起作用。
UiDevice device = UiDevice.getInstance(getInstrumentation());
device.pressHome();
device.pressRecentApps();
device.findObject(new UiSelector().text(getTargetContext().getString(getTargetContext().getApplicationInfo().labelRes)))
.click();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2741 次 |
最近记录: |