Tạo kiểm thử đo lường

Kiểm thử đo lường chạy thử nghiệm trên thiết bị Android, dù là thiết bị thực hay thiết bị mô phỏng. Do đó, các ứng dụng này có thể tận dụng các API khung Android. Do đó, kiểm thử đo lường cung cấp độ chân thực cao hơn kiểm thử cục bộ, mặc dù chạy chậm hơn nhiều.

Bạn chỉ nên sử dụng kiểm thử đo lường trong trường hợp phải kiểm thử hành vi của thiết bị thực. AndroidX Test cung cấp một số thư viện giúp bạn dễ dàng viết mã kiểm thử đo lường hơn khi cần.

Thiết lập môi trường thử nghiệm

Trong dự án Android Studio, bạn lưu trữ các tệp nguồn cho kiểm thử đo lường trong module-name/src/androidTest/java/. Thư mục này đã tồn tại khi bạn tạo một dự án mới và chứa một kiểm thử đo lường mẫu.

Trước khi bắt đầu, bạn nên thêm API AndroidX Test để có thể nhanh chóng xây dựng và chạy mã kiểm thử đo lường cho ứng dụng của mình. AndroidX Test bao gồm một trình chạy kiểm thử JUnit 4, AndroidJUnitRunner và các API cho kiểm thử chức năng trên giao diện người dùng như Espresso, Trình tự động hoá giao diện người dùng và Kiểm thử Compose.

Bạn cũng cần định cấu hình các phần phụ thuộc kiểm thử Android cho dự án để sử dụng trình chạy kiểm thử và các API quy tắc do AndroidX Test cung cấp.

Trong tệp build.gradle cấp cao nhất của ứng dụng, bạn cần chỉ định các thư viện này dưới dạng phần phụ thuộc:

dependencies {
    androidTestImplementation "androidx.test:runner:$androidXTestVersion"
    androidTestImplementation "androidx.test:rules:$androidXTestVersion"
    // Optional -- UI testing with Espresso
    androidTestImplementation "androidx.test.espresso:espresso-core:$espressoVersion"
    // Optional -- UI testing with UI Automator
    androidTestImplementation "androidx.test.uiautomator:uiautomator:$uiAutomatorVersion"
    // Optional -- UI testing with Compose
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
}

Bạn có thể tìm thấy các phiên bản mới nhất trong Ghi chú phát hành AndroidX và Ghi chú phát hành Giao diện người dùng Compose.

Để sử dụng các lớp kiểm thử JUnit 4 và có quyền truy cập vào các tính năng như lọc kiểm thử, hãy nhớ chỉ định AndroidJUnitRunner làm trình chạy đo lường kiểm thử mặc định trong dự án bằng cách thêm chế độ cài đặt sau vào tệp build.gradle cấp mô-đun của ứng dụng:

android {
    defaultConfig {
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
}

Tạo một lớp kiểm thử đo lường

Lớp kiểm thử đo lường của bạn phải là một lớp kiểm thử JUnit 4 tương tự như lớp được mô tả trong phần cách tạo kiểm thử cục bộ.

Để tạo một lớp kiểm thử JUnit 4 đo lường, hãy chỉ định AndroidJUnit4 làm trình chạy kiểm thử mặc định.

Ví dụ sau đây cho thấy cách bạn có thể viết một kiểm thử đo lường để xác minh rằng giao diện Parcelable được triển khai chính xác cho lớp LogHistory:

Kotlin

import android.os.Parcel
import android.text.TextUtils.writeToParcel
import androidx.test.filters.SmallTest
import androidx.test.runner.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith

const val TEST_STRING = "This is a string"
const val TEST_LONG = 12345678L

// @RunWith is required only if you use a mix of JUnit3 and JUnit4.
@RunWith(AndroidJUnit4::class)
@SmallTest
class LogHistoryAndroidUnitTest {
    private lateinit var logHistory: LogHistory

    @Before
    fun createLogHistory() {
        logHistory = LogHistory()
    }

    @Test
    fun logHistory_ParcelableWriteRead() {
        val parcel = Parcel.obtain()
        logHistory.apply {
            // Set up the Parcelable object to send and receive.
            addEntry(TEST_STRING, TEST_LONG)

            // Write the data.
            writeToParcel(parcel, describeContents())
        }

        // After you're done with writing, you need to reset the parcel for reading.
        parcel.setDataPosition(0)

        // Read the data.
        val createdFromParcel: LogHistory = LogHistory.CREATOR.createFromParcel(parcel)
        createdFromParcel.getData().also { createdFromParcelData: List<Pair<String, Long>> ->

            // Verify that the received data is correct.
            assertThat(createdFromParcelData.size).isEqualTo(1)
            assertThat(createdFromParcelData[0].first).isEqualTo(TEST_STRING)
            assertThat(createdFromParcelData[0].second).isEqualTo(TEST_LONG)
        }
    }
}

Java

import android.os.Parcel;
import android.util.Pair;
import androidx.test.runner.AndroidJUnit4;
import com.google.common.truth.Truth.assertThat;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

// @RunWith is required only if you use a mix of JUnit3 and JUnit4.
@RunWith(AndroidJUnit4.class)
public class LogHistoryAndroidUnitTest {

    public static final String TEST_STRING = "This is a string";
    public static final long TEST_LONG = 12345678L;
    private LogHistory mLogHistory;

    @Before
    public void createLogHistory() {
        mLogHistory = new LogHistory();
    }

    @Test
    public void logHistory_ParcelableWriteRead() {
        // Set up the Parcelable object to send and receive.
        mLogHistory.addEntry(TEST_STRING, TEST_LONG);

        // Write the data.
        Parcel parcel = Parcel.obtain();
        mLogHistory.writeToParcel(parcel, mLogHistory.describeContents());

        // After you're done with writing, you need to reset the parcel for reading.
        parcel.setDataPosition(0);

        // Read the data.
        LogHistory createdFromParcel = LogHistory.CREATOR.createFromParcel(parcel);
        List<Pair<String, Long>> createdFromParcelData
                = createdFromParcel.getData();

        // Verify that the received data is correct.
        assertThat(createdFromParcelData.size()).isEqualTo(1);
        assertThat(createdFromParcelData.get(0).first).isEqualTo(TEST_STRING);
        assertThat(createdFromParcelData.get(0).second).isEqaulTo(TEST_LONG);
    }
}

Chạy kiểm thử đo lường

Bạn có thể chạy kiểm thử đo lường trên thiết bị thực hoặc trình mô phỏng. Trong hướng dẫn về Android Studio, bạn có thể tìm hiểu cách:

Tài nguyên khác

Kiểm thử giao diện người dùng thường là các kiểm thử đo lường giúp xác minh hành vi chính xác của giao diện người dùng. Các kiểm thử này sử dụng các khung như Espresso hoặc Compose Test. Để tìm hiểu thêm, hãy đọc hướng dẫn kiểm thử giao diện người dùng.

Để biết thêm thông tin về cách sử dụng kiểm thử đo lường, hãy tham khảo các tài nguyên sau.

Mẫu