This tutorial describes how to write unit of measurement and instrumentation tests for your Android application. Information technology describes how to execute these tests via Android studio and Gradle. This tutorial assumes that you are familiar with Android programming in general.

one. Introduction into Android testing

i.1. Testing Android applications

Android applications run on a variety of devices. Also the Android framework and the surrounding open up source frameworks evolve at a loftier speed. To ensure that yous application works well, it is import to write software tests. This helps you to enhance and maintain the Android application.

Unit testing for Android can be classified into:

  • Local unit tests - tests which can run on the JVM.

  • Instrumented unit tests - tests which require the Android system.

Android testing categories

Local unit tests run much faster compared to the time required to deploy and run tests on an Android device. Prefer writing local unit of measurement tests and only run tests on Android, if you require a existent Android system.

If y'all write local unit test and have dependencies to Android API, you demand to replace them, e.g., via a mocking framework similar Mockito.

1.2. What to test on Android applications

Your test should focus on the business organisation logic of your application. A good dominion of thumb is to have the post-obit distribution of tests:

  • 70-lxxx % unit tests to ensure stability of your code basis

  • twenty-30 % functional tests to ensure that the application really works

  • some cross functional tests if your application integrates intensively with other Application components

Testing Strategy for Android

Y'all should exam your awarding at least on one device with the lowest possible configuration. In add-on y'all should test on ane device with the highest bachelor configuration, due east.g., pixel density, screen resolution to ensure that information technology works fine on these devices.

1.3. Tooling support for Android testing

The Android Testing Support library (ATSL) project from Google provides tooling for Android testing. For example, it (AndroidJUnitRunner).

If you run local unit tests, a special version of the android.jar (also known equally the Android mockable jar) is created past the tooling. This modified JAR file is provided to the unit test so that all fields, methods and classes are available. Whatever call to the Android mockable JAR results, by default, in an exception, but you lot tin configure Android to return default values. Come across Activating default render values for mocked methods in android.jar for details.

The library provides a JUnit 4-compatible examination runner (AndroidJUnitRunner), the Espresso test framework and the UI Automator test framework. Espresso exam framework can be used to exam the User Interface of your application. UI Automator allows to write cross application functional tests.

AndroidJunitRunner provides access to the instrumentation API, via the InstrumentationRegistery.

  • InstrumentationRegistry.getInstrumentation(), returns the Instrumentation currently running.

  • InstrumentationRegistry.getContext(), returns the Context of this Instrumentation's package.

  • InstrumentationRegistry.getTargetContext(), returns the application Context of the target awarding.

  • InstrumentationRegistry.getArguments(), returns a copy of arguments Bundle that was passed to this Instrumentation. This is useful when you desire to access the command line arguments passed to the instrumentation for your exam.

It as well gives access to the life wheel via the ActivityLifecycleMonitorRegistry.

1.4. Android project system for tests

The following is the default directory structure for your application and test code:

  • app/src/primary/java- for your source code of your principal application build

  • app/src/test/coffee - for any unit test which can run on the JVM

  • app/src/androidTest/java - for any exam which should run on an Android device

If you lot follow this conversion, the Android build arrangement runs your tests on the right target (JVM or Android device).

Solving the "fault indistinguishable files in path" mistake

If you receive the following error bulletin: "error duplicate files in path. Path in archive: LICENSE.txt" yous can add the following to your app/gradle.build file.

                            android {     packagingOptions {     exclude 'LICENSE.txt'     } }                          

two. Android unit of measurement testing

2.ane. Unit testing in Android

A unit test verifies in isolation the functionality of a sure component. For case, assume a button in an Android activeness is used to start some other activity. A unit of measurement test would determine, if the respective intent was issued, not if the second activeness was started

A unit tests for an Android awarding can be:

  • local unit of measurement test - which runs on the JVM

  • Android unit examination - which runs on the Android runtime

If they run on the JVM, they are executed against a modified version of the android.jar Android library. In this version all terminal modifiers have been stripped off. This makes it easier to use mocking libraries, similar Mockito.

The local unit tests of an Android project should be located in the app/src/test folder.

two.two. Required dependencies in the Gradle build file

To use JUnit tests for your Android awarding, yous need to add it every bit dependency to your Gradle build file.

                                      dependencies                    {                    // Unit testing dependencies                    testCompile                    'junit:junit:4.12'                    // Gear up this dependency if y'all want to use the Hamcrest matcher library                    testCompile                    'org.hamcrest:hamcrest-library:1.3'                    // more stuff, e.g., Mockito                    }                                  

ii.3. Running the unit of measurement tests

2.three.1. Using Gradle

Run your unit of measurement tests with the gradlew test command.

two.iii.two. Using Android Studio

To run a unit test, right-click on your test form in the Project window and select Run.

Running Unit tests in Android Studio

2.iv. Location of test reports

The Test reports are created in the app/build/reports/tests/debug/ directory. The index.html gives an overview and links to the individual test pages.

2.5. Activating default return values for mocked methods in android.jar

By default, all calls to methods in the modified android.jar file throw exceptions. This default should ensure that your unit tests only test your code and do not depend on whatsoever particular behavior of the Android platform. If you want to configure a certain behavior, you can use a mocking framework to supervene upon these call.

You tin also instruct the Gradle build organisation to return default values for method calls in the `android.jar`with the following configuration in your Gradle build file.

                                      android                    {                    // ...                    testOptions                    {                    unitTests                    .                    returnDefaultValues                    =                    true                    }                    }                                  

3. Do: Create unit test

In this exercise y'all learn how to create a simple JUnit4 test for an Android project.

3.two. Add JUnit dependency

Ensure yous have the dependency to Junit in your app/build.gradle file.

                  dependencies {     // Unit testing dependencies     testImplementation 'junit:junit:4.12' }                

3.3. Create test

In your app/src/test directory create the post-obit two test methods for the ConverterUtil course.

                                      package                    com.vogella.android.temperature.exam                    ;                    import                    static                    org                    .                    junit                    .                    Assert                    .*;                    import                    org.junit.After                    ;                    import                    org.junit.Before                    ;                    import                    org.junit.Exam                    ;                    import                    com.vogella.android.temperature.ConverterUtil                    ;                    public                    class                    ConverterUtilTest                    {                    @Examination                    public                    void                    testConvertFahrenheitToCelsius                    ()                    {                    float                    actual                    =                    ConverterUtil                    .                    convertCelsiusToFahrenheit                    (                    100                    );                    // expected value is 212                    bladder                    expected                    =                    212                    ;                    // use this method considering bladder is non precise                    assertEquals                    (                    "Conversion from celsius to fahrenheit failed"                    ,                    expected                    ,                    actual                    ,                    0.001                    );                    }                    @Test                    public                    void                    testConvertCelsiusToFahrenheit                    ()                    {                    float                    actual                    =                    ConverterUtil                    .                    convertFahrenheitToCelsius                    (                    212                    );                    // expected value is 100                    float                    expected                    =                    100                    ;                    // use this method because float is non precise                    assertEquals                    (                    "Conversion from celsius to fahrenheit failed"                    ,                    expected                    ,                    actual                    ,                    0.001                    );                    }                    }                                  

3.4. Run unit tests

Ensure your unit tests are correctly implemented by running test tests. They should run successfully.

four. Writing tests to run on the Android device

4.1. Instrumentation tests

The Android testing API provides hooks into the Android component and awarding life cycle. These hooks are called the instrumentation API and allow your tests to control the life cycle and user interaction events.

Under normal circumstances your awarding cannot control the life bicycle events and the user drives the application. For instance, if Android creates your activity the onCreate() method is called. Or if the user presses a push button your corresponding code is chosen. Via instrumentation you can control these events via your test code. For instance, your instrumentation test can start the activeness. Afterwards, it can call the finish() and restart the activity to test if the case country of the activity is correctly restored.

Instrumented unit tests are unit tests that run on Android devices and emulators instead of running on the Java virtual machine. These tests have access to the existent device and its resources and are useful to unit of measurement test functionality which cannot be easily mocked past mocking frameworks. An instance is a examination which validates a Parcelable implementation.

An instrumentation-based test class allows yous to send key events (or touch events) to the application under test.

With user interface testing framework similar Espresso, the developer rarely has to apply the instrumentation API directly.

iv.ii. How the Android system executes tests

The InstrumentationTestRunner is the base examination runner for Android tests. This test runner starts and loads the test methods. Via the instrumentation API it communicates with the Android organisation. If y'all start a test for an Android application, the Android system kills whatever process of the application under exam and and then loads a new example. It does not offset the application, this is the responsibility of the test methods. The examination method controls the life cycle of the components of the application.

The test runner besides calls the onCreate() method of the application and activity under test during its initialization.

4.3. Mocking objects in Android

The mocking framework Mockito can too be used for instrumentation tests. This allows you to replace parts of the Android organisation which are not interesting for the test. The Android framework provided in the past specialized mocking classes but these are not necessary anymore.

iv.4. Location of instrumentation tests

Every bit described in Android project organization for tests the unit tests of an Android project should be located in the app/src/androidTest/java folder.

4.5. Ascertain dependencies and testInstrumentationRunner in the Gradle build file

To use JUnit tests for your Android application you need to add together the dependency to JUnit to your Gradle build file. Yous also demand to specify android.back up.test.runner.AndroidJUnitRunner as testInstrumentationRunner in the build file.

                  defaultConfig {        ..... more stuff         testInstrumentationRunner "android.support.examination.runner.AndroidJUnitRunner"     }  dependencies {     // Unit testing dependencies     androidTestCompile 'junit:junit:4.12'     // Gear up this dependency if y'all desire to apply the Hamcrest matcher library     androidTestCompile 'org.hamcrest:hamcrest-library:1.iii'     // more stuff, e.yard., Mockito }                

iv.6. Using the @RunWith(AndroidJUnit4.grade)

It is as well recommended annotating the test with the @RunWith(AndroidJUnit4.class) notation. AndroidJUnit4 extends JUnit4, and so if you use pure Junit4 syntax and ActivityTestRule it is not required. Merely yous need it, if y'all want to run, i.e., Espresso tests with ActivityTestRule and JUnit4.

4.7. Run the tests on Android

Run your local unit tests via Gradle with the gradlew connectedCheck control.

To run your local unit tests via Android Studio, right-click on your exam class in the Project window and select Run.

4.viii. Location of test reports

The test reports are created in the app/build/reports/androidTests/connected/ directory. The index.html gives an overview and links to the individual exam pages.

iv.9. How to replace the application for instrumentation tests

Yous can replace the awarding class for the instrumentation tests past overriding the AndroidJUnitRunner and its newApplication method.

                                      package                    com.vogella.android.daggerjunitmockito                    ;                    import                    android.app.Application                    ;                    public                    form                    MyMockApplication                    extends                    Application                    {                    @Override                    public                    void                    onCreate                    ()                    {                    // do something important for your tests here                    }                    }                                  

Examination runner

                                      package                    com.vogella.android.daggerjunitmockito                    ;                    import                    android.app.Application                    ;                    import                    android.content.Context                    ;                    import                    android.support.test.runner.AndroidJUnitRunner                    ;                    public                    class                    MockTestRunner                    extends                    AndroidJUnitRunner                    {                    @Override                    public                    Application                    newApplication                    (                    ClassLoader                    cl                    ,                    Cord                    className                    ,                    Context                    context                    )                    throws                    InstantiationException                    ,                    IllegalAccessException                    ,                    ClassNotFoundException                    {                    return                    super                    .                    newApplication                    (                    cl                    ,                    MyMockApplication                    .                    class                    .                    getName                    (),                    context                    );                    }                    }                                  

And yous need to register this test runner in your build.gradle file.

                                      android                    {                    /// more                    testInstrumentationRunner                    "com.vogella.android.daggerjunitmockito.MockTestRunner"                    }                    /// more than                    }                                  

5. Exercise: Write Android instrumentation test and use mocking

This exercise demonstrates the usage of the Mockito framework for Android tests.

v.i. Create class to test

Add the following utility form.

                                      parcel                    com.vogella.android.test.juntexamples.util                    ;                    import                    android.content.Context                    ;                    import                    java.io.FileOutputStream                    ;                    public                    form                    WriteConfigurationUtil                    {                    public                    static                    void                    writeConfiguration                    (                    Context                    ctx                    )                    {                    try                    (                    FileOutputStream                    openFileOutput                    =                    ctx                    .                    openFileOutput                    (                    "config.txt"                    ,                    Context                    .                    MODE_PRIVATE                    );)                    {                    openFileOutput                    .                    write                    (                    "This is a test1."                    .                    getBytes                    ());                    openFileOutput                    .                    write                    (                    "This is a test2."                    .                    getBytes                    ());                    }                    take hold of                    (                    Exception                    eastward                    )                    {                    // not handled                    }                    }                    }                                  

v.2. Create a new unit of measurement test

Write a unit test which validates that: * openFileOutput is called exactly once * the write() method is called at least twice.

                                      package                    com.vogella.android.exam.juntexamples.mockitotests                    ;                    import                    android.content.Context                    ;                    import                    com.vogella.android.test.juntexamples.util.Util                    ;                    import                    org.junit.Rule                    ;                    import                    org.junit.Test                    ;                    import                    org.mockito.Mock                    ;                    import                    org.mockito.junit.MockitoJUnit                    ;                    import                    org.mockito.junit.MockitoRule                    ;                    import                    java.io.FileOutputStream                    ;                    import                    static                    org                    .                    junit                    .                    Assert                    .                    fail                    ;                    import                    static                    org                    .                    mockito                    .                    Matchers                    .                    whatsoever                    ;                    import                    static                    org                    .                    mockito                    .                    Matchers                    .                    anyInt                    ;                    import                    static                    org                    .                    mockito                    .                    Matchers                    .                    anyString                    ;                    import                    static                    org                    .                    mockito                    .                    Mockito                    .                    atLeast                    ;                    import                    static                    org                    .                    mockito                    .                    Mockito                    .                    times                    ;                    import                    static                    org                    .                    mockito                    .                    Mockito                    .                    verify                    ;                    import                    static                    org                    .                    mockito                    .                    Mockito                    .                    when                    ;                    public                    class                    WriteConfigurationUtilTest                    {                    @Rule                    public                    MockitoRule                    rule                    =                    MockitoJUnit                    .                    rule                    ();                    @Mock                    Context                    context                    ;                    @Mock                    FileOutputStream                    fileOutputStream                    ;                    @Examination                    public                    void                    writeShouldWriteTwiceToFileSystem                    ()                    {                    try                    {                    when                    (                    context                    .                    openFileOutput                    (                    anyString                    (),                    anyInt                    ())).                    thenReturn                    (                    fileOutputStream                    );                    Util                    .                    writeConfiguration                    (                    context                    );                    verify                    (                    context                    ,                    times                    (                    ane                    )).                    openFileOutput                    (                    anyString                    (),                    anyInt                    ());                    verify                    (                    fileOutputStream                    ,                    atLeast                    (                    2                    )).                    write                    (                    any                    (                    byte                    [].                    form                    ));                    }                    catch                    (                    Exception                    e                    )                    {                    e                    .                    printStackTrace                    ();                    fail                    ();                    }                    }                    }                                  

This test requires a dependency to the Mockito test framework.

6. More on Android testing

half dozen.1. Test groups

The @SmallTest, @MediumTest and @LargeTest annotations allows to classify tests.

This allows yous to run, for instance, merely short running tests. You may run your long running tests on a continuous integration server.

To run merely selected tests you lot can configure the InstrumentationTestRunner via your Gradle plug-in. The following listing is an example for your build.gradle file to run only the tests annotated with @SmallTests.

                                      android                    {                    //....                    defaultConfig                    {                    //....                    testInstrumentationRunner                    "android.support.test.runner.AndroidJUnitRunner"                    testInstrumentationRunnerArgument                    "size"                    ,                    "small"                    }                    }                                  
                                      import                    android.test.suitebuilder.notation.MediumTest                    ;                    import                    android.test.suitebuilder.annotation.SmallTest                    ;                    import                    org.junit.Examination                    ;                    public                    class                    ExampleTest                    {                    @Test                    @SmallTest                    public                    void                    validateSecondActivity                    ()                    {                    // Do something not so long...                    }                    @Examination                    @MediumTest                    public                    void                    validateSecondActivityAgain                    ()                    {                    // Do something which takes more time....                    }                    }                                  

half dozen.2. Exam filtering

You tin annotate tests with annotations. The Android test runner allows to filter these tests.

Table i. Annotations for filtering tests
Annotation Clarification

@RequiresDevice

Specifies that the test should run merely on physical devices, non on emulators.

@SdkSupress

@SDKSupress(minSdkVersion=eighteen)

half-dozen.3. Flaky tests

Actions in Android are sometimes time dependent. To tell Android to repeat a exam in one case it fails, use the @FlakyTest annotation. Via the tolerance attribute of this notation yous can ascertain how many times the exam should be repeated before marking information technology as failed.

vii. Testing Android components

7.1. Activity testing

To test an activity, you employ the ActivityTestRule class provided past the Android Testing Back up Library.

This dominion provides functional testing of a single activity. The activity under test will be launched earlier each exam annotated with @Test and before any method annotated with @Earlier. It volition be terminated subsequently the test is completed and all methods annotated with @After are finished. The Activity under Test tin can be accessed during your test by calling ActivityTestRule#getActivity().

                                      package                    com.vogella.android.exam.examples                    ;                    import                    android.support.exam.filters.MediumTest                    ;                    import                    android.support.test.rule.ActivityTestRule                    ;                    import                    android.support.test.runner.AndroidJUnit4                    ;                    import                    android.view.View                    ;                    import                    android.widget.ArrayAdapter                    ;                    import                    android.widget.ListAdapter                    ;                    import                    android.widget.ListView                    ;                    import                    org.junit.Rule                    ;                    import                    org.junit.Test                    ;                    import                    org.junit.runner.RunWith                    ;                    import                    static                    org                    .                    hamcrest                    .                    Matchers                    .                    greaterThan                    ;                    import                    static                    org                    .                    hamcrest                    .                    Matchers                    .                    instanceOf                    ;                    import                    static                    org                    .                    hamcrest                    .                    Matchers                    .                    notNullValue                    ;                    import                    static                    org                    .                    junit                    .                    Affirm                    .                    assertThat                    ;                    @MediumTest                    @RunWith                    (                    AndroidJUnit4                    .                    course                    )                    public                    class                    MainActivityTest                    {                    @Rule                    public                    ActivityTestRule                    <                    MainActivity                    >                    rule                    =                    new                    ActivityTestRule                    <>(                    MainActivity                    .                    class                    );                    @Test                    public                    void                    ensureListViewIsPresent                    ()                    throws                    Exception                    {                    MainActivity                    action                    =                    rule                    .                    getActivity                    ();                    View                    viewById                    =                    activeness                    .                    findViewById                    (                    R                    .                    id                    .                    listview                    );                    assertThat                    (                    viewById                    ,                    notNullValue                    ());                    assertThat                    (                    viewById                    ,                    instanceOf                    (                    ListView                    .                    class                    ));                    ListView                    listView                    =                    (                    ListView                    )                    viewById                    ;                    ListAdapter                    adapter                    =                    listView                    .                    getAdapter                    ();                    assertThat                    (                    adapter                    ,                    instanceOf                    (                    ArrayAdapter                    .                    class                    ));                    assertThat                    (                    adapter                    .                    getCount                    (),                    greaterThan                    (                    5                    ));                    }                    }                                  

To configure the intent which is used to offset the activeness, override ActivityTestRule#getActivityIntent.

                                      package                    com.vogella.android.test.examples                    ;                    import                    android.content.Intent                    ;                    import                    android.support.examination.InstrumentationRegistry                    ;                    import                    android.support.test.filters.MediumTest                    ;                    import                    android.support.test.dominion.ActivityTestRule                    ;                    import                    android.support.test.runner.AndroidJUnit4                    ;                    import                    android.view.View                    ;                    import                    android.widget.ListView                    ;                    import                    android.widget.TextView                    ;                    import                    org.junit.Rule                    ;                    import                    org.junit.Examination                    ;                    import                    org.junit.runner.RunWith                    ;                    import                    static                    org                    .                    hamcrest                    .                    Matchers                    .                    instanceOf                    ;                    import                    static                    org                    .                    hamcrest                    .                    Matchers                    .                    is                    ;                    import                    static                    org                    .                    hamcrest                    .                    Matchers                    .                    notNullValue                    ;                    import                    static                    org                    .                    junit                    .                    Assert                    .                    assertThat                    ;                    @MediumTest                    @RunWith                    (                    AndroidJUnit4                    .                    grade                    )                    public                    class                    SecondActivityTest                    {                    @Rule                    public                    ActivityTestRule                    <                    SecondActivity                    >                    rule                    =                    new                    ActivityTestRule                    <                    SecondActivity                    >(                    SecondActivity                    .                    class                    )                    {                    @Override                    protected                    Intent                    getActivityIntent                    ()                    {                    InstrumentationRegistry                    .                    getTargetContext                    ();                    Intent                    intent                    =                    new                    Intent                    (                    Intent                    .                    ACTION_MAIN                    );                    intent                    .                    putExtra                    (                    "MYKEY"                    ,                    "Howdy"                    );                    return                    intent                    ;                    }                    };                    @Examination                    public                    void                    ensureIntentDataIsDisplayed                    ()                    throws                    Exception                    {                    SecondActivity                    activity                    =                    dominion                    .                    getActivity                    ();                    View                    viewById                    =                    activity                    .                    findViewById                    (                    R                    .                    id                    .                    target                    );                    assertThat                    (                    viewById                    ,                    notNullValue                    ());                    assertThat                    (                    viewById                    ,                    instanceOf                    (                    TextView                    .                    form                    ));                    TextView                    textView                    =                    (                    TextView                    )                    viewById                    ;                    assertThat                    (                    textView                    .                    getText                    ().                    toString                    (),                    is                    (                    "How-do-you-do"                    ));                    }                    }                                  

7.2. Service testing

To examination a service, y'all employ the ServiceTestRule course provided by the Android Testing Support Library.

This rule provides a simplified mechanism to start and shutdown your service before and after your exam. Information technology guarantees that the service is successfully connected when starting (or bounden to) a service. The service tin can be started (or bound) using one of the helper methods. Information technology will automatically be stopped (or unbound) after the examination completes and any methods annotated with @After are finished.

This rule doesn't support IntentService, because information technology'south automatically destroyed later on the onHandleIntent method.

The following listing is an example of testing a service.

                                      @RunWith                    (                    AndroidJUnit4                    .                    class                    )                    @MediumTest                    public                    class                    MyServiceTest                    {                    @Rule                    public                    final                    ServiceTestRule                    mServiceRule                    =                    new                    ServiceTestRule                    ();                    // exam for a service which is started with startService                    @Exam                    public                    void                    testWithStartedService                    ()                    {                    mServiceRule                    .                    startService                    (                    new                    Intent                    (                    InstrumentationRegistry                    .                    getTargetContext                    (),                    MyService                    .                    class                    ));                    // test code                    }                    @Test                    // examination for a service which is started with bindService                    public                    void                    testWithBoundService                    ()                    {                    IBinder                    binder                    =                    mServiceRule                    .                    bindService                    (                    new                    Intent                    (                    InstrumentationRegistry                    .                    getTargetContext                    (),                    MyService                    .                    class                    ));                    MyService                    service                    =                    ((                    MyService                    .                    LocalBinder                    )                    binder                    ).                    getService                    ();                    assertTrue                    (                    "True wasn't returned"                    ,                    service                    .                    doSomethingToReturnTrue                    ());                    }                    }                                  
                  adb kill-server adb start-server                

7.3. Receiver testing

Receivers can exist tested directly. Assume the post-obit receiver.

                                      public                    grade                    OutgoingCallReceiver                    extends                    BroadcastReceiver                    {                    @Override                    public                    void                    onReceive                    (                    Context                    ctx                    ,                    Intent                    i                    )                    {                    if                    (                    i                    .                    getAction                    ().                    equalsIgnoreCase                    (                    Intent                    .                    ACTION_NEW_OUTGOING_CALL                    ))                    {                    String                    phoneNum                    =                    i                    .                    getStringExtra                    (                    Intent                    .                    EXTRA_PHONE_NUMBER                    );                    Intent                    intent                    =                    new                    Intent                    (                    ctx                    ,                    MyActivity                    .                    class                    );                    intent                    .                    putExtra                    (                    "phoneNum"                    ,                    phoneNum                    );                    intent                    .                    addFlags                    (                    Intent                    .                    FLAG_ACTIVITY_NEW_TASK                    );                    ctx                    .                    startActivity                    (                    intent                    );                    }                    }                    }                                  

You tin can test information technology, via an instrumented exam and Mockito.

                                      @Test                    public                    void                    testStartActivity                    ()                    {                    // prepare information for onReceive and telephone call it                    Intent                    intent                    =                    new                    Intent                    (                    Intent                    .                    ACTION_NEW_OUTGOING_CALL                    );                    intent                    .                    putExtra                    (                    Intent                    .                    EXTRA_PHONE_NUMBER                    ,                    "01234567890"                    );                    mReceiver                    .                    onReceive                    (                    mContext                    ,                    intent                    );                    assertNull                    (                    mReceiver                    .                    getResultData                    ());                    // what did receiver do?                    ArgumentCaptor                    <                    Intent                    >                    argument                    =                    ArgumentCaptor                    .                    forClass                    (                    Intent                    .                    grade                    );                    verify                    (                    mContext                    ,                    times                    (                    ane                    )).                    startActivity                    (                    statement                    .                    capture                    ());                    Intent                    receivedIntent                    =                    argument                    .                    getValue                    ();                    assertNull                    (                    receivedIntent                    .                    getAction                    ());                    assertEquals                    (                    "01234567890"                    ,                    receivedIntent                    .                    getStringExtra                    (                    "phoneNum"                    ));                    assertTrue                    ((                    receivedIntent                    .                    getFlags                    ()                    &                    Intent                    .                    FLAG_ACTIVITY_NEW_TASK                    )                    !=                    0                    );                    }                                  

7.four. Content provider testing

To test a content provider, y'all use the ProviderTestCase2 grade. ProviderTestCase2 automatically instantiates the provider under test and inserts an IsolatedContext object. This context is isolated from the Android arrangement, but however allows file and database access. The usage of the IsolatedContext object ensures that your provider examination does not bear on the real device.

ProviderTestCase2 also provides access to a MockContentResolver via the getMockContentResolver() method.

You lot should exam all operations of the provider and likewise what happens if the provider is called with an invalid URI or with an invalid projection.

seven.five. Loader testing

To test a loader, you use the `LoaderTestCase`course. It is expected that a JUnit 4 rule volition be provided in the future to replace this grade.

8. Application testing

The application class contains the logic, data and settings which are relevant for the whole application. Therefore you should exam this object, to ensure it works correctly.

You can write a JUnit 4 test for the application object and test information technology on the JVM. In this case you would mock all dependencies to the awarding object.

To test an Android application object on the Android runtime you employ the ApplicationTestCase class. Information technology would be slap-up if Google would provide a special JUnit4 rule for testing the application object, but at the moment this is not yet available.

The examination runner of the Android tests (InstrumentationTestRunner) creates automatically an instance of application during its initialization stage. If you do asynchronous processing in your onCreate method you should consider that.

9. Exercise: Testing the Android application

In this practise you learn how to write tests for your awarding object.

9.1. Create project

Create a new Android application with the com.vogella.android.testing.applicationtest parcel name based on the Empty Activity template.

Add together the following application object to your application.

                                      package                    com.vogella.android.testing.applicationtest                    ;                    import                    android.app.Awarding                    ;                    import                    coffee.util.ArrayList                    ;                    import                    java.util.Listing                    ;                    public                    form                    MyApplication                    extends                    Application                    {                    public                    static                    terminal                    Listing                    <                    String                    >                    list                    =                    new                    ArrayList                    <                    String                    >();                    }                                  

Too declare the application it in your manifest file.

                                      <?xml version="1.0" encoding="utf-8"?>                    <manifest                    xmlns:android=                    "http://schemas.android.com/apk/res/android"                    package=                    "com.vogella.android.testing.applicationtest"                    >                    <application                    android:name=                    ".MyApplication"                    android:allowBackup=                    "truthful"                    android:icon=                    "@mipmap/ic_launcher"                    android:label=                    "@cord/app_name"                    android:theme=                    "@style/AppTheme"                    >                    <activity                    android:proper noun=                    ".MainActivity"                    android:characterization=                    "@cord/app_name"                    >                    <intent-filter>                    <activity                    android:name=                    "android.intent.action.MAIN"                    />                    <category                    android:proper noun=                    "android.intent.category.LAUNCHER"                    />                    </intent-filter>                    </activity>                    </application>                    </manifest>                                  

9.2. Create unit examination for application object

In your app/src/test directory create a new unit test. Assert that the MyApplication.list field is not empty and has initially a size of nix.

9.3. Create instrumented test for application object

Create the following unit of measurement exam based on the JUnit 3 testing framework.

                                      package                    com.vogella.android.testing.applicationtest                    ;                    import                    android.content.pm.PackageInfo                    ;                    import                    android.examination.ApplicationTestCase                    ;                    import                    android.test.MoreAsserts                    ;                    public                    class                    ApplicationTest                    extends                    ApplicationTestCase                    <                    MyApplication                    >                    {                    private                    MyApplication                    application                    ;                    public                    ApplicationTest                    ()                    {                    super                    (                    MyApplication                    .                    form                    );                    }                    protected                    void                    setUp                    ()                    throws                    Exception                    {                    super                    .                    setUp                    ();                    createApplication                    ();                    application                    =                    getApplication                    ();                    }                    public                    void                    testCorrectVersion                    ()                    throws                    Exception                    {                    PackageInfo                    info                    =                    application                    .                    getPackageManager                    ().                    getPackageInfo                    (                    application                    .                    getPackageName                    (),                    0                    );                    assertNotNull                    (                    info                    );                    MoreAsserts                    .                    assertMatchesRegex                    (                    "\\d\\.\\d"                    ,                    info                    .                    versionName                    );                    }                    }                                  

10. Creating lawmaking coverage written report

A code coverage report shows you how much of your application code is covered by tests. To create such a written report, you tin create a dissever launch configuration. For this, select your package and select card:[Create Tests in…​].

android code coverage10

You lot can now create a runtime configuration for the code coverage. If you run it a study is generated.

android code coverage20

android code coverage30

android code coverage40

11. Using the Monkey tool for creating a random event stream

11.1. What is monkey?

Monkey is a command line tool which sends pseudo random events to your device. Y'all can restrict Monkey to run just for a certain bundle and therefore instruct Monkey to test only your application.

xi.2. How to use Monkey

The following command sends 2000 random events to the application with the de.vogella.android.test.target package.

                  adb beat out monkey                    -p                    de.vogella.android.test.target                    -v                    2000                

Monkey sometimes causes problems with the adb server. Use the following commands to restart the adb server.

                  adb kill-server adb start-server                

Yous tin use the -due south [seed] parameter to ensure that the generated sequence of events is always the same.

13. Test folder cosmos in Android Studio

The recent versions of Android Studio has added a test binder to its default project template. In case you are using a template which does non create a test binder, you have to create information technology manually. To create the exam folder in Android Studio, switch to the Project view, this shows you the directory structure of your project.

Switching to the Project view in Android Studio

Select the src and apply the context bill of fare to create a new test binder.

Switching to the Project view in Android Studio

Adding a java folder

Adding a java folder

If not yet done, also add the JUnit dependency to your Gradle build file.

                                  dependencies                  {                  // Unit testing dependencies                  testCompile                  'junit:junit:iv.12'                  // Set up this dependency if you want to utilise the Hamcrest matcher library                  testCompile                  'org.hamcrest:hamcrest-library:1.3'                  // more than stuff, e.thou., Mockito                  }                              

The creation of the Java binder might add the new test directory as source file to your build.gradle file. If you have the post-obit entry in your app/build.gradle file you need to REMOVE it. test should NOT be treated equally normal source binder.

                                                      sourceSets                            {                            main                            {                            java                            .                            srcDirs                            =                            [                            '                            src                            /                            master                            /                            coffee                            '                            ,                            '                            src                            /                            test                            /                            java                            /                            '                            ]                            }                            }                                                  

Afterwards you can add your unit of measurement test to this folder structure.

14. Android testing resources

AndroidToolsStaticChecks[Using static checks in Android for your code]