Android testing official tutorial translation -- building device unit tests

  • There are hardly any errors in translation, please point out the mistakes. If you do not understand anything, please refer to the official English information.
  • mock object and mocking framework also appeared many times in the first two blog posts. I don’t know how to translate them, so I translated them into imitation objects and imitation frameworks.
  • Some parts of the test suite in this article are translated into test suites, and some places use English directly
  • Official original link Building Instrumented Unit Tests

Device unit testing

Device unit tests are tests that run on physical devices and emulators, and they can take advantage of Android Framework APIs and supporting APIs, such as the Android Testing Support Library. If your tests need to obtain instrumentation information (such as the target app's context) or need the actual implementation of Android framework components (such as Parcelable o or SharedPreferences objects), you should create device unit tests.

Using device unit tests can also reduce the effort of writing and maintaining mock code. You can still use the mocking framework, if you choose to, to mock any dependencies.

Set up your test environment

In your AndroidStudio project, you must store the source files for device tests in the path module-name/src/androidTest/java/ . This path already exists when you create a new project, and contains an example of a device test.

Before you start, you should download Android Testing Support Library Setup , which provides APIs that allow you to quickly build and run device test code against your app. Testing Support Library contains a JUnit 4 test runner and APIs for functional UI testing (Espresso and UI Automator, see translation 1 for the link).

You also need to configure Android test dependencies for your project to use the test runner and rule s provided by the Testing Support Library. To simplify the test environment, you should introduce Hamcrest Libraries that allow you to create more flexible assertion s using the Hamcrest matcher APIs.

In your App's top-level build.gradle file, you need to specify these libraries as dependencies.

dependencies {
    androidTestCompile ''
    androidTestCompile ''
    androidTestCompile ''
    // Optional -- Hamcrest library
    androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
    // Optional -- UI testing with Espresso
    androidTestCompile ''
    // Optional -- UI testing with UI Automator
    androidTestCompile ''

Note: If your build configuration includes the compile dependency of the support-annotations library and the androidTestCompile dependency of the espresso-core library, your build may fail due to dependency conflicts. To fix the problem, update the espresso-core dependency as follows.

androidTestCompile('', {
    exclude group: '', module: 'support-annotations'

Create a device unit test class

Your device unit test classes should be written like JUnit 4 test classes. To learn more about creating JUnit 4 test classes and using assertion s and annotation s, see "Creating Native Unit Test Classes".

To create a device JUnit 4 test class, add the annotation @RunWith(AndroidJUnit4.class) at the beginning of the test class definition. You also need to specify the AndroidJUnitRunner provided by the Android Testing Support Library as the default test runner. This step is described in detail in Getting Started with Testing.

The following example shows how you can write a device unit test to test that the Parcelable interface of the LogHistory class is implemented correctly.

import android.os.Parcel;
import android.util.Pair;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import static;
import static org.junit.Assert.assertThat;

public class LogHistoryAndroidUnitTest {

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

    public void createLogHistory() {
        mLogHistory = new LogHistory();

    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.

        // 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(), is(1));
        assertThat(createdFromParcelData.get(0).first, is(TEST_STRING));
        assertThat(createdFromParcelData.get(0).second, is(TEST_LONG));

Create a test suite

To organize the execution of device unit tests, you can group test classes in a test suite class and run the test classes together.

A test suite is contained in a test package, similar to the main application package. By convention, test suite package names often end with a .suite suffix (eg
To create a test suite for unit testing, import JUnit's RunWith and Suite classes. In your test suite, add @RunWith(Suite.class) and @Suite.SuitClasses() annotations. In @Suite.SuitClasses(), list individual test classes or test suite s as parameters.

The following example shows how you can implement a test suite of class named UnitTestSuite that groups and runs the CalculatorInstrumentationTest and CalculatorAddParameterizedTest test classes together.

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

// Runs all unit tests.
public class UnitTestSuite {}

Run device unit tests

To run device unit tests, follow the steps below.

  1. Click Sync Project on the toolbar , to ensure that the project and gradle are in sync.
  2. Run the test in one of the following ways
    • To run a single test, open the Project window, then right-click a test and click Run
    • To test all methods in a class, right-click a class or method in the test file and click Run
    • To run all tests under a path, right-click the path and select Run Tests

The Android gradle plugin compiles the device test code located in the default path (src/androidTest/java/), builds a test APK and a production APK (production APK), installs both APKs on a connected device or emulator, and runs test. Android Studio then displays the results of the device test execution in the Run window.

When running or debugging device tests, Android Studio does not inject the extra methods and shutdown features required by Instant Run.

Run tests with Firebase Test Lab

use Firebase Test Lab , you can simultaneously test your App on many popular devices and device configurations (region, orientation, screen size, and platform version). The tests were run on physical and virtual devices in remote google data centers. You can deploy app s directly to Test Lab via Android Studio or the command line. Test results provide test logs and include details of any App failures.

Before you start using Firebase Test Lab, you need to follow the steps below, unless you already have a Google account and a Firebase project.

  1. If you don't have an account, Create a Google Account .
  2. exist Firebase console , click Create new project.
    exist Spark Plan: Free Daily Quota Inside, use the Test Lab to test the App for free.

PS: This part has not been translated, and there is not much left. Considering that google services cannot be used in China/charged/I do not have this demand, I will not translate the remaining part.

Tags: Android unit testing

Posted by Hellbringer2572 on Mon, 11 Jul 2022 01:57:50 +0530