Android测试教程(14):ActivityInstrumentationTestCase2示例

jerry Android 2015年08月24日 收藏

ActivityInstrumentationTestCase2 用來測試單個的Activity,被測試的Activity可以使用InstrumentationTestCase.launchActivity 來啟動,然後你能夠直接操作被測試的Activity。

ActivityInstrumentationTestCase2 也支持:

  • 可以在UI線程中運行測試方法.
  • 可以注入Intent對象到被測試的Activity中

ActivityInstrumentationTestCase2 取代之前的ActivityInstrumentationTestCase ,新的測試應該使用ActivityInstrumentationTestCase2作為基類。

Focus2ActivityTest 的代碼如下,用於測試Android ApiDemos示例解析(116):Views->Focus->2. Horizontal

  1. public class Focus2ActivityTest
  2. extends ActivityInstrumentationTestCase2<Focus2> {
  3.  
  4. private Button mLeftButton;
  5. private Button mCenterButton;
  6. private Button mRightButton;
  7.  
  8. public Focus2ActivityTest() {
  9. super("com.example.android.apis", Focus2.class);
  10. }
  11.  
  12. @Override
  13. protected void setUp() throws Exception {
  14. super.setUp();
  15. final Focus2 a = getActivity();
  16. mLeftButton = (Button) a.findViewById(R.id.leftButton);
  17. mCenterButton = (Button) a.findViewById(R.id.centerButton);
  18. mRightButton = (Button) a.findViewById(R.id.rightButton);
  19. }
  20.  
  21.  
  22. @MediumTest
  23. public void testPreconditions() {
  24. assertTrue("center button should be right of left button",
  25. mLeftButton.getRight() < mCenterButton.getLeft());
  26. assertTrue("right button should be right of center button",
  27. mCenterButton.getRight() < mRightButton.getLeft());
  28. assertTrue("left button should be focused", mLeftButton.isFocused());
  29. }
  30.  
  31. @MediumTest
  32. public void testGoingRightFromLeftButtonJumpsOverCenterToRight() {
  33. sendKeys(KeyEvent.KEYCODE_DPAD_RIGHT);
  34. assertTrue("right button should be focused", mRightButton.isFocused());
  35. }
  36.  
  37. @MediumTest
  38. public void testGoingLeftFromRightButtonGoesToCenter()  {
  39.  
  40. getActivity().runOnUiThread(new Runnable() {
  41. public void run() {
  42. mRightButton.requestFocus();
  43. }
  44. });
  45. // wait for the request to go through
  46. getInstrumentation().waitForIdleSync();
  47.  
  48. assertTrue(mRightButton.isFocused());
  49.  
  50. sendKeys(KeyEvent.KEYCODE_DPAD_LEFT);
  51. assertTrue("center button should be focused",
  52. mCenterButton.isFocused());
  53. }
  54. }

setUp 中初始化mLeftButton,mCenterButton和mRightButton,調用每個測試方法之前,setUp 都會被調用。

testPreconditions 通常為第一個測試方法,用來檢測後續的測試環境是否符合條件。

testGoingRightFromLeftButtonJumpsOverCenterToRight 中調用sendKeys 可以模擬按鍵消息。

testGoingLeftFromRightButtonGoesToCenter 中 ,使用runOnUiThread 來為mRightButton 請求focus ,使用runOnUiThread 的原因是因為本測試方法不在UI線程中運行。  getInstrumentation 可以取得Instrumentation對象,有了Instrumentation 對象就可以對Activity進行大部分的操作,waitForIdleSync() 等待application 回到idle 狀態,之後就可以檢測mRightButton 是否獲得了焦點。