简体   繁体   English

Android Activity生命周期测试

[英]Android Activity lifecycle testing

I have Activity, which is to save its data in case system decides to kill it while it is in the background. 我有Activity,这是为了保存它的数据,以防系统决定在它在后台时杀死它。 So, I've got onSaveInstanceState: 所以,我有onSaveInstanceState:

@Override
protected void onSaveInstanceState(Bundle outState){
    outState.putString("value", "some_value");
}

I check whether Bundle object is null in onCreate: 我在onCreate中检查Bundle对象是否为null:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    isRestarted=(savedInstanceState==null);

How do I write test method? 我该如何编写测试方法? I tried 我试过了

    public void testRecreate(){
    Instrumentation mInstr=this.getInstrumentation();
    mInstr.callActivityOnSaveInstanceState(mActivity, null);
    mActivity.finish();
    mActivity=this.getActivity();
    assertEquals(false, mActivity.isRestarted);
}

but it seems to be wrong. 但似乎是错的。

You can use some hidden API functionality. 您可以使用一些隐藏的API功能。 In your test's setup, call the 在您的测试设置中,请致电

android.app.ActivityManagerNative.getDefault().setAlwaysFinish()

method via reflection (because it's a hidden API) and confirm that the value was successfully set using 方法通过反射(因为它是一个隐藏的API)并确认使用了成功设置的值

android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ALWAYS_FINISH_ACTIVITIES, 0)

Then in the test cleanup, set this setting back to false. 然后在测试清理中,将此设置设置为false。

Enabling the AlwaysFinish setting causes the system to destroy activities as soon as they are no longer on the screen, immediately triggering the onSaveInstanceState event. 启用AlwaysFinish设置会导致系统在屏幕上不再显示活动时立即销毁活动,立即触发onSaveInstanceState事件。 For this code to work, you will need the ALWAYS_FINISH and WRITE_SETTINGS permissions. 要使此代码ALWAYS_FINISH ,您需要ALWAYS_FINISHWRITE_SETTINGS权限。

See the code for the SetAlwaysFinish tool linked in this blog: How to test onSaveInstanceState and onRestoreInstanceState on a real device 请参阅此博客中链接的SetAlwaysFinish工具的代码: 如何在真实设备上测试onSaveInstanceState和onRestoreInstanceState

For manual testing, this routine works: 对于手动测试,此例程有效:

  1. Launch the activity you want to test 启动要测试的活动
  2. Hit the home menu button on your device (activity is stopped) 点击设备上的主菜单按钮(停止活动)
  3. Kill the process from DDMS (activity is still not destroyed ) DDMS中杀死进程(活动仍未被破坏
  4. Bring back your app again from the recent apps list 最近的应用列表中再次恢复您的应用

This should trigger onCreate again on your activity while not restarting the entire application. 这应该在您的活动上再次触发onCreate ,而不是重新启动整个应用程序。 If you're not saving and loading the state properly, you'll know soon enough. 如果您没有正确保存和加载状态,您很快就会知道。

如果您之前没有通过它,我发现至少有一次这样做是值得的。

Stuff like that could be easily test using robolectric . 这样的东西很容易用robolectric进行测试。 Check it out! 看看这个!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM