ActivityInstrumentationTestCase2 用來測試單個的Activity,被測試的Activity可以使用InstrumentationTestCase.launchActivity 來啟動,然後你能夠直接操作被測試的Activity。
ActivityInstrumentationTestCase2 也支持:
- 可以在UI線程中運行測試方法.
- 可以注入Intent對象到被測試的Activity中
ActivityInstrumentationTestCase2 取代之前的ActivityInstrumentationTestCase ,新的測試應該使用ActivityInstrumentationTestCase2作為基類。
Focus2ActivityTest 的代碼如下,用於測試Android ApiDemos示例解析(116):Views->Focus->2. Horizontal
public class Focus2ActivityTest extends ActivityInstrumentationTestCase2<Focus2> { private Button mLeftButton; private Button mCenterButton; private Button mRightButton; public Focus2ActivityTest() { super("com.example.android.apis", Focus2.class); } @Override protected void setUp() throws Exception { super.setUp(); final Focus2 a = getActivity(); mLeftButton = (Button) a.findViewById(R.id.leftButton); mCenterButton = (Button) a.findViewById(R.id.centerButton); mRightButton = (Button) a.findViewById(R.id.rightButton); } @MediumTest public void testPreconditions() { assertTrue("center button should be right of left button", mLeftButton.getRight() < mCenterButton.getLeft()); assertTrue("right button should be right of center button", mCenterButton.getRight() < mRightButton.getLeft()); assertTrue("left button should be focused", mLeftButton.isFocused()); } @MediumTest public void testGoingRightFromLeftButtonJumpsOverCenterToRight() { sendKeys(KeyEvent.KEYCODE_DPAD_RIGHT); assertTrue("right button should be focused", mRightButton.isFocused()); } @MediumTest public void testGoingLeftFromRightButtonGoesToCenter() { getActivity().runOnUiThread(new Runnable() { public void run() { mRightButton.requestFocus(); } }); // wait for the request to go through getInstrumentation().waitForIdleSync(); assertTrue(mRightButton.isFocused()); sendKeys(KeyEvent.KEYCODE_DPAD_LEFT); assertTrue("center button should be focused", mCenterButton.isFocused()); } }
setUp 中初始化mLeftButton,mCenterButton和mRightButton,調用每個測試方法之前,setUp 都會被調用。
testPreconditions 通常為第一個測試方法,用來檢測後續的測試環境是否符合條件。
testGoingRightFromLeftButtonJumpsOverCenterToRight 中調用sendKeys 可以模擬按鍵消息。
testGoingLeftFromRightButtonGoesToCenter 中 ,使用runOnUiThread 來為mRightButton 請求focus ,使用runOnUiThread 的原因是因為本測試方法不在UI線程中運行。 getInstrumentation 可以取得Instrumentation對象,有了Instrumentation 對象就可以對Activity進行大部分的操作,waitForIdleSync() 等待application 回到idle 狀態,之後就可以檢測mRightButton 是否獲得了焦點。