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

Android Studio 測試實戰:單元測試與 UI 測試的完整流程解析

編輯:關於 Android 開發

一、配置支援單元測試的專案

在動手寫測試之前,先做一次簡單的檢查,確保專案配置正確。首先,確認在 Build Variants 視窗中的 Test Artifact 選擇了「Unit Tests」。接著,在專案的 src 資料夾內建立 test 與 test/java 資料夾。需要注意的是,你無法在 Android 視圖下完成這些操作,必須切換到 Project 視圖,或直接在系統檔案管理器中建立。最後,開啟 build.gradle (Module: app),加入 JUnit4 依賴並點擊 Gradle sync:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
    testCompile 'junit:junit:4.12'
}

二、建立第一個單元測試

先建立一個簡單的被測類 Calculator,暫時讓所有方法回傳 0:

public class Calculator {
    public double sum(double a, double b) { return 0; }
    public double substract(double a, double b) { return 0; }
    public double divide(double a, double b) { return 0; }
    public double multiply(double a, double b) { return 0; }
}

Android Studio 提供了快速建立測試類的方法:在編輯器中右鍵點擊 Calculator 類的宣告,選擇 Go to → Test → Create a new test,在彈出的視窗中選擇 JUnit4 與 setUp/@Before,並為所有運算方法生成測試框架。生成的測試類如下:

public class CalculatorTest {
    private Calculator mCalculator;

    @Before
    public void setUp() throws Exception {
        mCalculator = new Calculator();
    }

    @Test
    public void testSum() throws Exception {
        assertEquals(6d, mCalculator.sum(1d, 5d), 0);
    }

    @Test
    public void testSubstract() throws Exception {
        assertEquals(1d, mCalculator.substract(5d, 4d), 0);
    }

    @Test
    public void testDivide() throws Exception {
        assertEquals(4d, mCalculator.divide(20d, 5d), 0);
    }

    @Test
    public void testMultiply() throws Exception {
        assertEquals(10d, mCalculator.multiply(2d, 5d), 0);
    }
}

三、運行單元測試

右鍵點擊 CalculatorTest 類,選擇 Run → CalculatorTest;也可以在命令列輸入 ./gradlew test 來運行。此時你會看到 4 個測試全部失敗——這是預期中的結果,因為我們還沒實作運算邏輯。接著把 sum 方法改成正確的實作:

public double sum(double a, double b) {
    return a + b;
}

重新運行後,你會看到 4 個測試中有 3 個失敗。作為練習,你可以逐一實作剩餘方法,讓所有測試通過。

值得留意的是,Android Studio 從頭到尾都沒讓你連接裝置或啟動模擬器。這是因為位於 src/test 目錄下的測試,是運行在本地電腦 Java 虛擬機上的單元測試。這種「寫測試 → 實作功能讓測試通過 → 再補更多測試」的工作方式,讓快速迭代成為可能,我們稱之為測試驅動開發(TDD)。由於本地測試時 Gradle 提供的 android.jar 功能並不完整,建議搭配 Mockito 等 mocking 框架來模擬所需的 Android 方法。

四、配置支援 Instrumentation 測試的專案

要在真機或模擬器上執行充分利用 Android 框架的測試,需要使用 Android Testing Support Library 中的 AndroidJUnitRunner,並搭配 UI 測試框架 Espresso。編輯 build.gradle 加入相關配置:

android {
    defaultConfig {
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    packagingOptions {
        exclude 'LICENSE.txt'
    }
}
dependencies {
    compile 'com.android.support:appcompat-v7:22.0.0'
    testCompile 'junit:junit:4.12'
    androidTestCompile 'com.android.support.test:runner:0.2'
    androidTestCompile 'com.android.support.test:rules:0.2'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.1'
}

重要:由於依賴版本衝突,務必確認 appcompat-v7 的版本號為 22.0.0。此外,Android Studio 可能提示 Build Tools 22.0.1 未安裝,接受修復建議即可。

五、為 app 添加簡單的互動

在進行 Espresso UI 測試前,先為 app 加入一個可輸入名字的 EditText、一個歡迎用的 Button 與一個輸出的 TextView。開啟 res/layout/activity_main.xml 貼入佈局,並在 MainActivity 中加入 onClick 處理:

public void sayHello(View v) {
    TextView textView = (TextView) findViewById(R.id.textView);
    EditText editText = (EditText) findViewById(R.id.editText);
    textView.setText("Hello, " + editText.getText().toString() + "!");
}

六、建立並運行 Espresso 測試

在專案中找出以(androidTest)結尾的套件,建立一個新的 Java 類 MainActivityInstrumentationTest:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityInstrumentationTest {
    private static final String STRING_TO_BE_TYPED = "Peter";

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule =
            new ActivityTestRule<>(MainActivity.class);

    @Test
    public void sayHello() {
        onView(withId(R.id.editText)).perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard());
        onView(withText("Say hello!")).perform(click());
        String expectedText = "Hello, " + STRING_TO_BE_TYPED + "!";
        onView(withId(R.id.textView)).check(matches(withText(expectedText)));
    }
}

測試類透過 AndroidJUnitRunner 運行,並執行 sayHello() 方法。逐行來看:

  1. 找到 ID 為 editText 的 view,輸入 Peter,然後關閉鍵盤;
  2. 點擊顯示「Say hello!」的按鈕(由於未設 id,透過文字搜尋定位);
  3. 比對 TextView 上的文字與預期結果,一致則測試通過。

右鍵點擊並選擇 Run 即可運行測試,這會在模擬器或已連接的裝置上執行,你能在手機螢幕上看到實際的操作過程(例如在 EditText 上打字),最後 Android Studio 會輸出通過與失敗的測試結果。

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