是否有一种简单的方法来模拟按下Robolectric中的后退按钮?
以下测试失败:
@Test
public void testBackButtonClosesActivity() throws Exception {
ShadowActivity activityShadow = Shadows.shadowOf(activity);
activity.onKeyDown(KeyEvent.KEYCODE_BACK, new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK, 0));
assertTrue(activityShadow.isFinishing());
}
然而,这成功了:
@Test
public void testBackButtonClosesActivity() throws Exception {
ShadowActivity activityShadow = Shadows.shadowOf(activity);
activity.onBackPressed();
assertTrue(activityShadow.isFinishing());
}
我的活动是覆盖onKeyDown()
:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK & myCondition) {
doStuff();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
在myCondition
为真时进行测试会在使用doStuff()
的其他测试中触发activity.onKeyDown(KeyEvent.KEYCODE_BACK, new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK, 0));
。
使用以下方式创建活动:
Intent intent = new Intent(ShadowApplication.getInstance().getApplicationContext(), MyActivity.class);
activity = Robolectric.buildActivity(MyActivity.class).withIntent(intent).create().visible().get();
我应该指出当myCondition为false时按下应用程序中的后退按钮会导致活动关闭。