Home | History | Annotate | Download | only in unit-testing
      1 page.title=Building Instrumented Unit Tests
      2 page.tags=testing,androidjunitrunner,junit,unit test,mock,instrumentation
      3 trainingnavtop=true
      4 
      5 @jd:body
      6 
      7 <!-- This is the training bar -->
      8 <div id="tb-wrapper">
      9 <div id="tb">
     10   <h2>This lesson teaches you to</h2>
     11 
     12   <ol>
     13     <li><a href="#setup">Set Up Your Testing Environment</a></li>
     14     <li><a href="#build">Create a Instrumented Unit Test Class</a>
     15       <ol>
     16         <li><a href="#test-suites">Create a test suite</a></li>
     17       </ol>
     18     </li>
     19     <li><a href="#run">Run Instrumented Unit Tests</a>
     20       <ol>
     21         <li><a href="#run-ctl">Run your tests with Firebase Test Lab</a></li>
     22       </ol>
     23     </li>
     24   </ol>
     25 
     26   <h2>Try it out</h2>
     27 
     28   <ul>
     29     <li>
     30 <a href="https://github.com/googlesamples/android-testing/tree/master/unit/BasicUnitAndroidTest"
     31 class="external-link">Instrumented Unit Tests Code Samples</a></li>
     32     <li><a href="https://www.code-labs.io/codelabs/android-studio-testing/index.html?index=..%2F..%2Findex#0"
     33 class="external-link">Unit and UI Testing in Android Studio (codelab)</a></li>
     34   </ul>
     35 </div>
     36 </div>
     37 
     38 <p>Instrumented unit tests are tests that run on physical devices and
     39 emulators, and they can take advantage of the Android framework APIs and
     40 supporting APIs, such as the Android Testing Support Library. You should create
     41 instrumented unit tests if your tests need access to instrumentation
     42 information (such as the target app's {@link android.content.Context}) or if
     43 they require the real implementation of an Android framework component (such as
     44 a {@link android.os.Parcelable} or {@link android.content.SharedPreferences}
     45 object).</p>
     46 
     47 <p>Using instrumented unit tests also helps to reduce the effort required to
     48 write and maintain mock code. You are still free to use a mocking framework, if
     49 you choose, to simulate any dependency relationships.</p>
     50 
     51 
     52 <h2 id="setup">Set Up Your Testing Environment</h2>
     53 
     54 <p>In your Android Studio project, you must store the source files for
     55 instrumented tests at
     56 <code><var>module-name</var>/src/androidTests/java/</code>. This directory
     57 already exists when you create a new project.</p>
     58 
     59 <p>Before you begin, you should
     60   <a href="{@docRoot}tools/testing-support-library/index.html#setup">download
     61   the Android Testing Support Library Setup</a>, which provides APIs that allow
     62   you to quickly build and run instrumented test code for your apps. The
     63   Testing Support Library includes a JUnit 4 test runner (<a href=
     64   "{@docRoot}tools/testing-support-library/index.html#AndroidJUnitRunner">AndroidJUnitRunner</a>
     65   ) and APIs for functional UI tests (<a href=
     66   "{@docRoot}tools/testing-support-library/index.html#Espresso">Espresso</a>
     67   and <a href=
     68   "{@docRoot}tools/testing-support-library/index.html#UIAutomator">UI
     69   Automator</a>).
     70 </p>
     71 
     72 <p>You also need to configure the Android testing dependencies for your project
     73 to use the test runner and the rules APIs provided by the Testing Support
     74 Library. To simplify your test development, you should also include the
     75 <a href="https://github.com/hamcrest" class="external-link">Hamcrest</a>
     76 library, which lets you create more flexible assertions using the Hamcrest
     77 matcher APIs.</p>
     78 
     79 <p>
     80   In your app's top-level {@code build.gradle} file, you need to specify these
     81   libraries as dependencies:
     82 </p>
     83 
     84 <pre>
     85 dependencies {
     86     androidTestCompile 'com.android.support:support-annotations:24.0.0'
     87     androidTestCompile 'com.android.support.test:runner:0.5'
     88     androidTestCompile 'com.android.support.test:rules:0.5'
     89     // Optional -- Hamcrest library
     90     androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
     91     // Optional -- UI testing with Espresso
     92     androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
     93     // Optional -- UI testing with UI Automator
     94     androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.2'
     95 }
     96 </pre>
     97 
     98 
     99 <p>
    100   To use JUnit 4 test classes, make sure to specify <a href=
    101   "{@docRoot}reference/android/support/test/runner/AndroidJUnitRunner.html">{@code
    102   AndroidJUnitRunner}</a> as the default test instrumentation runner in your
    103   project by including the following setting in your app's module-level {@code build.gradle}
    104   file:
    105 </p>
    106 
    107 <pre>
    108 android {
    109     defaultConfig {
    110         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    111     }
    112 }
    113 </pre>
    114 
    115 
    116 
    117 
    118 <h2 id="build">Create an Instrumented Unit Test Class</h2>
    119 
    120 <p>
    121 Your instrumented unit test class should be written as a JUnit 4 test class. To learn more about
    122 creating JUnit 4 test classes and using JUnit 4 assertions and annotations, see
    123 <a href="local-unit-tests.html#build">Create a Local Unit Test Class</a>.
    124 </p>
    125 <p>To create an instrumented JUnit 4 test class, add the {@code &#64;RunWith(AndroidJUnit4.class)}
    126 annotation at the beginning of your test class definition. You also need to specify the
    127 <a href="{@docRoot}reference/android/support/test/runner/AndroidJUnitRunner.html">
    128 {@code AndroidJUnitRunner}</a> class
    129 provided in the Android Testing Support Library as your default test runner. This step is described
    130 in more detail in <a href="{@docRoot}training/testing/start/index.html#run-instrumented-tests">
    131 Getting Started with Testing</p>
    132 
    133 <p>The following example shows how you might write an instrumented unit test to test that
    134 the {@link android.os.Parcelable} interface is implemented correctly for the
    135 {@code LogHistory} class:</p>
    136 
    137 <pre>
    138 import android.os.Parcel;
    139 import android.support.test.runner.AndroidJUnit4;
    140 import android.util.Pair;
    141 import org.junit.Test;
    142 import org.junit.runner.RunWith;
    143 import java.util.List;
    144 import static org.hamcrest.Matchers.is;
    145 import static org.junit.Assert.assertThat;
    146 
    147 &#64;RunWith(AndroidJUnit4.class)
    148 &#64;SmallTest
    149 public class LogHistoryAndroidUnitTest {
    150 
    151     public static final String TEST_STRING = "This is a string";
    152     public static final long TEST_LONG = 12345678L;
    153     private LogHistory mLogHistory;
    154 
    155     &#64;Before
    156     public void createLogHistory() {
    157         mLogHistory = new LogHistory();
    158     }
    159 
    160     &#64;Test
    161     public void logHistory_ParcelableWriteRead() {
    162         // Set up the Parcelable object to send and receive.
    163         mLogHistory.addEntry(TEST_STRING, TEST_LONG);
    164 
    165         // Write the data.
    166         Parcel parcel = Parcel.obtain();
    167         mLogHistory.writeToParcel(parcel, mLogHistory.describeContents());
    168 
    169         // After you're done with writing, you need to reset the parcel for reading.
    170         parcel.setDataPosition(0);
    171 
    172         // Read the data.
    173         LogHistory createdFromParcel = LogHistory.CREATOR.createFromParcel(parcel);
    174         List&lt;Pair&lt;String, Long&gt;&gt; createdFromParcelData = createdFromParcel.getData();
    175 
    176         // Verify that the received data is correct.
    177         assertThat(createdFromParcelData.size(), is(1));
    178         assertThat(createdFromParcelData.get(0).first, is(TEST_STRING));
    179         assertThat(createdFromParcelData.get(0).second, is(TEST_LONG));
    180     }
    181 }
    182 </pre>
    183 
    184 <h3 id="test-suites">Create a test suite</h3>
    185 <p>
    186 To organize the execution of your instrumented unit tests, you can group a collection of test
    187 classes in a <em>test suite</em> class and run these tests together. Test suites can be nested;
    188 your test suite can group other test suites and run all their component test classes together.
    189 </p>
    190 
    191 <p>
    192 A test suite is contained in a test package, similar to the main application package. By
    193 convention, the test suite package name usually ends with the {@code .suite} suffix (for example,
    194 {@code com.example.android.testing.mysample.suite}).
    195 </p>
    196 
    197 <p>
    198 To create a test suite for your unit tests, import the JUnit
    199 <a href="http://junit.sourceforge.net/javadoc/org/junit/runner/RunWith.html"
    200 class="external-link">{@code RunWith}</a> and
    201 <a href="http://junit.sourceforge.net/javadoc/org/junit/runners/Suite.html"
    202 class="external-link">{@code Suite}</a> classes. In your test suite, add the
    203 {@code &#64;RunWith(Suite.class)} and the {@code &#64;Suite.SuitClasses()} annotations. In
    204 the {@code &#64;Suite.SuiteClasses()} annotation, list the individual test classes or test
    205 suites as arguments.
    206 </p>
    207 
    208 <p>
    209 The following example shows how you might implement a test suite called {@code UnitTestSuite}
    210 that groups and runs the {@code CalculatorInstrumentationTest} and
    211 {@code CalculatorAddParameterizedTest} test classes together.
    212 </p>
    213 
    214 <pre>
    215 import com.example.android.testing.mysample.CalculatorAddParameterizedTest;
    216 import com.example.android.testing.mysample.CalculatorInstrumentationTest;
    217 import org.junit.runner.RunWith;
    218 import org.junit.runners.Suite;
    219 
    220 // Runs all unit tests.
    221 &#64;RunWith(Suite.class)
    222 &#64;Suite.SuiteClasses({CalculatorInstrumentationTest.class,
    223         CalculatorAddParameterizedTest.class})
    224 public class UnitTestSuite {}
    225 </pre>
    226 
    227 
    228 <h2 id="run">Run Instrumented Unit Tests</h2>
    229 
    230 <p>To run your instrumented tests, follow these steps:</p>
    231 
    232 <ol>
    233   <li>Be sure your project is synchronized with Gradle by clicking
    234   <b>Sync Project</b> <img src="/images/tools/sync-project.png" alt=""
    235   class="inline-icon"> in the toolbar.</li>
    236 
    237   <li>Run your test in one of the following ways:
    238     <ul>
    239       <li>To run a single test, open the <b>Project</b> window, and then
    240   right-click a test and click <strong>Run</strong> <img src=
    241   "{@docRoot}images/tools/as-run.png" alt="" class="inline-icon">.</li>
    242       <li>To test all methods in a class, right-click a class or method in the
    243 test file and click <b>Run</b> <img src=
    244   "{@docRoot}images/tools/as-run.png" alt="" class="inline-icon">.
    245       <li>To run all tests in a directory, right-click on the
    246       directory and select <strong>Run tests</strong> <img src=
    247       "{@docRoot}images/tools/as-run.png" alt="" class="inline-icon">.
    248       </li>
    249     </ul>
    250   </li>
    251 
    252 </ol>
    253 
    254 <p>
    255   The <a href="{@docRoot}tools/building/plugin-for-gradle.html">Android Plugin
    256   for Gradle</a> compiles the instrumented test code located in the default
    257   directory ({@code src/androidTest/java/}), builds a test APK and production
    258   APK, installs both APKs on the connected device or emulator, and runs the
    259   tests. Android Studio then displays the results of the instrumented test execution in the
    260   <em>Run</em> window.
    261 </p>
    262 
    263 <p class="note">
    264   <strong>Note:</strong> While running or debugging instrumented tests,
    265   Android Studio does not inject the additional methods required for <a href=
    266   "{@docRoot}tools/building/building-studio.html#instant-run">Instant Run</a>
    267   and turns the feature off.
    268 </p>
    269 
    270 
    271 <h3 id="run-ctl">Run your tests with Firebase Test Lab</h3>
    272 
    273 <p>Using <a href="https://firebase.google.com/docs/test-lab/">Firebase Test
    274 Lab</a>, you can simultaneously test your app on many popular Android devices
    275 and configurations such as locale, orientation, screen size, and platform
    276 version. These tests run on actual physical devices in remote Google data
    277 centers. You can deploy to Firebase Test Lab directly from Android Studio or
    278 from the command line. Test results provide test logs and include the details
    279 of any app failures.</p>
    280 
    281 <p>
    282   Before you can start using Firebase Test Lab, you need to:
    283 </p>
    284 
    285 <ol>
    286   <li>
    287     <a href="https://console.developers.google.com/freetrial">Create a
    288     Google Cloud Platform account</a> to use with active billing.
    289   </li>
    290 
    291   <li>
    292     <a href="https://support.google.com/cloud/answer/6251787">Create a Google
    293     Cloud project</a> for your app.
    294   </li>
    295 
    296   <li>
    297     <a href="https://support.google.com/cloud/answer/6288653">Set up an active
    298     billing account</a> and associate it with the project you just created.
    299   </li>
    300 </ol>
    301 
    302 
    303 <h4 id="configure-matrix">
    304 Configure a test matrix and run a test
    305 </h4>
    306 
    307 <p>
    308   Android Studio provides integrated tools that allow you to configure how you
    309  want to deploy your tests to Firebase Test Lab. After you have created a Google
    310   Cloud project with active billing, you can create a test configuration and
    311   run your tests:
    312 </p>
    313 
    314 <ol>
    315   <li>Click <strong>Run</strong> &gt; <strong>Edit Configurations</strong> from
    316   the main menu.
    317   </li>
    318 
    319   <li>Click <strong>Add New Configuration (+)</strong> and select
    320   <strong>Android Tests</strong>.
    321   </li>
    322 
    323   <li>In the Android Test configuration dialog:
    324     <ol type="a">
    325       <li>Enter or select the details of your test, such as the test name, module
    326       type, test type, and test class.
    327       </li>
    328 
    329       <li>From the <em>Target</em> drop-down menu under <em>Deployment Target
    330       Options</em>, select <strong>Cloud Test Lab Device Matrix</strong>.
    331       </li>
    332 
    333       <li>If you are not logged in, click <strong>Connect to Google Cloud
    334       Platform</strong> and allow Android Studio access to your account.
    335       </li>
    336 
    337       <li>Next to <em>Cloud Project</em>, click the <img src=
    338       "{@docRoot}images/tools/as-wrench.png" alt="wrench and nut" style=
    339       "vertical-align:bottom;margin:0;"> button and select your Google Cloud
    340       Platform project from the list.
    341       </li>
    342     </ol>
    343   </li>
    344 
    345   <li>Create and configure a test matrix:
    346     <ol type="a">
    347       <li>Next to the <em>Matrix Configuration</em> drop-down list, click <strong>
    348         Open Dialog</strong> <img src="{@docRoot}images/tools/as-launchavdm.png"
    349         alt="ellipses button" style="vertical-align:bottom;margin:0;">.
    350       </li>
    351 
    352       <li>Click <strong>Add New Configuration (+)</strong>.
    353       </li>
    354 
    355       <li>In the <strong>Name</strong> field, enter a name for your new
    356       configuration.
    357       </li>
    358 
    359       <li>Select the device(s), Android version(s), locale(s) and screen
    360       orientation(s) that you want to test your app with. Firebase Test Lab will
    361       test your app against every combination of your selections when generating
    362       test results.
    363       </li>
    364 
    365       <li>Click <strong>OK</strong> to save your configuration.
    366       </li>
    367     </ol>
    368   </li>
    369 
    370   <li>Click <strong>OK</strong> in the <em>Run/Debug Configurations</em> dialog
    371   to exit.
    372   </li>
    373 
    374   <li>Run your tests by clicking <strong>Run</strong> <img src=
    375   "{@docRoot}images/tools/as-run.png" alt="" style=
    376   "vertical-align:bottom;margin:0;">.
    377   </li>
    378 </ol>
    379 
    380 <img src="{@docRoot}images/training/ctl-config.png" alt="">
    381 <p class="img-caption">
    382   <strong>Figure 1.</strong> Creating a test configuration for Firebase Test
    383   Lab.
    384 </p>
    385 
    386 <h4 id="ctl-results">
    387   Analyzing test results
    388 </h4>
    389 
    390 <p>
    391   When Firebase Test Lab completes running your tests, the <em>Run</em> window
    392   will open to show the results, as shown in figure 2. You may need to click
    393   <strong>Show Passed</strong> <img src="{@docRoot}images/tools/as-ok.png" alt=
    394   "" style="vertical-align:bottom;margin:0;"> to see all your executed tests.
    395 </p>
    396 
    397 <img src="{@docRoot}images/training/ctl-test-results.png" alt="">
    398 
    399 <p class="img-caption">
    400   <strong>Figure 2.</strong> Viewing the results of instrumented tests using
    401   Firebase Test Lab.
    402 </p>
    403 
    404 <p>
    405   You can also analyze your tests on the web by following the link displayed at
    406   the beginning of the test execution log in the <em>Run</em> window, as shown
    407   in figure 3.
    408 </p>
    409 
    410 <img src="{@docRoot}images/training/ctl-exec-log.png" alt="">
    411 
    412 <p class="img-caption">
    413   <strong>Figure 3.</strong> Click the link to view detailed test results on
    414   the web.
    415 </p>
    416 
    417 <p>
    418   To learn more about interpreting web results, see <a href=
    419   "https://firebase.google.com/docs/test-lab/analyzing-results">Analyze
    420   Firebase Test Lab for Android Results</a>.
    421 </p>