Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 應用程式測試實務:從測試專案到 UI 驗證

編輯:關於 Android 程式設計

一、建立測試環境

安裝了 ADT 外掛的 Eclipse 提供圖形化的開發環境,其中一項便利功能是能自動為 Android 應用專案建立對應的測試專案。

第一步,建立一個 Android 專案(例如 AndroidNormalProject),或匯入既有專案:

第二步,在專案上按右鍵選擇 Android Tools → New Test Project... 產生測試專案:

二、建立與執行測試案例

測試程式碼務必放在獨立的套件中,和被測試的程式碼分離。慣例是沿用應用程式套件名並在後方加上 .tests;測試案例的類別名稱則是被測類別名加上 Test 後綴。

專案套件:

測試套件:

建立測試夾具(Fixture)

測試夾具負責初始化測試所需的物件。覆寫 setUp() 與 tearDown(),前者會在其他測試方法之前自動執行,用來保持初始化與清理邏輯分離。

import android.test.ActivityInstrumentationTestCase2;
import android.widget.TextView;
import com.example.androidnormalproject.MainActivity;
import com.example.androidnormalproject.R;

public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {

    private MainActivity mMainActivity;
    private TextView mTextView;

    public MainActivityTest() {
        super(MainActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        mMainActivity = getActivity();
        mTextView = (TextView) mMainActivity.findViewById(R.id.helloword_text);
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
    }
}

加上前置條件檢查

public void testPreconditions() {
    assertNotNull("MainActivity 不應為 null", mMainActivity);
    assertNotNull("TextView 不應為 null", mTextView);
}

驗證 Activity 的內容

public void testMainActivityTextView_helloword() {
    final String expected = mMainActivity.getString(R.string.hello_world);
    final String actual = mTextView.getText().toString();
    assertEquals(expected, actual);
}

執行測試

選擇 Run As → Android JUnit Test:

三、測試 UI 元件

驗證按鈕的布局

/** 測試 Button 的布局屬性 */
public void testMainActivityButton_layout() {
    final View decorView = mMainActivity.getWindow().getDecorView();
    // 確認按鈕在螢幕範圍內
    ViewAsserts.assertOnScreen(decorView, mButton);

    final ViewGroup.LayoutParams layoutParams = mButton.getLayoutParams();
    assertNotNull(layoutParams);
    assertEquals(layoutParams.width, WindowManager.LayoutParams.MATCH_PARENT);
    assertEquals(layoutParams.height, WindowManager.LayoutParams.WRAP_CONTENT);
}

驗證按鈕的行為

/** 測試按鈕點擊事件 */
public void testMainActivityButton_onClick() {
    String expectedInfoText = mMainActivity.getString(R.string.button_text);
    TouchUtils.clickView(this, mButton);
    assertTrue(View.VISIBLE == mButton.getVisibility());
    assertEquals(expectedInfoText, mButton.getText());
}

值得注意的是,TouchUtils 的作用是把事件安全地從其他線程派送到 UI 線程,因此不該在 UI 線程的測試中使用它。

測試規模標註

  • @SmallTest:小型測試,通常是最小單元。
  • @MediumTest:中型測試。
  • @LargeTest:大型測試,涵蓋跨元件流程。

總結

有了上述方法,就能建立單元測試(驗證可能性最小的程式碼區塊)與功能測試(驗證單一元件是否如預期與其他元件協同運作)。需要補充的是,ActivityInstrumentationTestCase2 這套 API 在 Instrumentation 測試框架下已屬舊世代,新專案建議改用 AndroidX Test 的 ActivityScenario 與 Espresso,並以 JUnit 4 撰寫測試,能獲得更穩定的生命週期管理與更簡潔的 UI 操作語法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved