1

如何使用 Instrumentation 从 TestCase 中控制 Android Activity 的生命周期?

官方文档中,声明“生命周期控制:通过检测,您可以使用测试用例类提供的方法启动、暂停和销毁被测活动。”。当然,使用这个测试用例,Acitivity 会在调用 getActivity() 时自动创建,并在每个测试用例之后停止。但是如何从外部控制生命周期以检查所有生命周期方法是否正确实现?

生命周期方法 onActivityXXX 只是帮助调用相应的方法,但不会导致 Activity 暂停或停止。谁能帮助并告诉我我必须使用哪些方法?

是否有任何方法可以测试 Android 应用程序的生命周期实现?

4

1 回答 1

1

这不会让您完全控制生命周期,但它是此处的示例:

// Start the main activity of the application under test
    mActivity = getActivity();

    // Get a handle to the Activity object's main UI widget, a Spinner
    mSpinner = (Spinner)mActivity.findViewById(com.android.example.spinner.R.id.Spinner01);

    // Set the Spinner to a known position
    mActivity.setSpinnerPosition(TEST_STATE_DESTROY_POSITION);

    // Stop the activity - The onDestroy() method should save the state of the Spinner
    mActivity.finish();

    // Re-start the Activity - the onResume() method should restore the state of the Spinner
    mActivity = getActivity();

    // Get the Spinner's current position
    int currentPosition = mActivity.getSpinnerPosition();

    // Assert that the current position is the same as the starting position
    assertEquals(TEST_STATE_DESTROY_POSITION, currentPosition);

这使您可以控制主要的生命周期事件。我目前正在处理同样的问题,我正在研究应该有帮助的机器人

于 2015-05-26T10:13:24.610 回答