Android Test (v): instrumented unit Test

Source: Internet
Author: User

Android Test (v): instrumented unit Test

Release date December 20, 2017 bug Master

Original: https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html

Instrumented unit testing is a test run on a real machine and emulator that leverages the Android framework API and supported APIs such as the Android Test support library. If your test requires access to tool information, such as the target application Context , or if you need to really implement an Android framework component such as Parcelable or an SharedPreferences object, you should create a instrumented unit test.

Using instrumented unit tests also helps reduce the effort required to write and maintain mock code. If you want, you can still freely use a mock frame to simulate any dependency relationship.

Setting up a test environment

In your Android studio project, you must store the source files for the mock test in module-name/src/androidtest/java/. The catalog already exists when you create a new project and contains sample code.

Before you begin, you should download the Android Test Support Library installer, which provides APIs that allow you to quickly build and run your application's instrumentation code. The Test support library includes the JUnit 4 Test Runner (Androidjunitrunner) and APIs for functional UI testing (espresso and UI Automator).

You also need to configure Android test dependencies for your project to use the rule APIs provided by the Test runner and the test support library. To simplify test development, you should also include the Hamcrest library, which allows you to create more flexible assertions using the Hamcrest match API.

Specify these libraries as dependencies in your app's top-level Build.gradle file:

 dependencies {    androidtestcompile  com.android.support:support-annotations:24.0.0 '     androidtestcompile  com.android.support.test:runner:0.5 '     androidtestcompile  com.android.support.test:rules:0.5 '     //Optional--Hamcrest library    Androidtestcompile  ' org.hamcrest:hamcrest-library:1.3 '     //Optional-UI testing with espresso    androidtestcompile  com.android.support.test.espresso:espresso-core:2.2.2 '     //Optional--UI Testing with UI automator    androidtestcompile  com.android.support.test.uiautomator:uiautomator-v18:2.1.2 '}        

Warning: If the build configuration contains the compilation dependencies of the Support-annotations library and the Androidtestcompile dependencies of the Espresso-core library, the build may fail due to a dependency conflict. Follow the steps below to update the dependency on Espresso-core:

androidTestCompile(‘com.android.support.test.espresso:espresso-core:2.2.2‘, {    exclude group: ‘com.android.support‘, module: ‘support-annotations‘})

To use the JUnit 4 test class, be sure to designate Androidjunitrunner as the default test tool runner in your project by including the following settings in your application's module-level Build.gradle file:

"android.support.test.runner.AndroidJUnitRunner"    }}
To create a instrumented unit test class

Your instrumented unit test class should be written as a JUnit 4 test class. To learn more about creating JUnit 4 test classes and using JUnit 4 assertions and annotations, see Creating a local unit test class.

To create a instrumented JUnit 4 test class, add a @runwith (androidjunit4.class) comment at the beginning of the test class definition. You also need to designate the Androidjunitrunner class provided in the Android Test support library as the default Test Runner. This step is described in more detail in getting started with the test.

The following example shows how to write a instrumented unit test to ensure that the Loghistory class implements the Parcelable interface correctly:

Import Android.os.Parcel;Import ANDROID.SUPPORT.TEST.RUNNER.ANDROIDJUNIT4;Import Android.util.Pair;Import Org.junit.Test;Import Org.junit.runner.RunWith;Import java.util.List;ImportStatic org.hamcrest.Matchers.is;ImportStatic org.junit.Assert.assertThat;@RunWith (Androidjunit4.class)@SmallTestPublicClassloghistoryandroidunittest {PublicStaticFinal String test_string ="This is a string";PublicStaticFinalLong Test_long =12345678L;Private Loghistory mloghistory;@BeforePublicvoidCreateloghistory() {mloghistory =New Loghistory (); }@TestPublicvoidLoghistory_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-do with writing, you need-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 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 test unit tests, you can set up a set of tests in a test suite class and run them together. Test suite can be nested; The test suite can group other test suites and run all the component test classes together.

The test suite is included in the test package, similar to the main application package. By convention, the test suite package name usually .suite ends with a suffix (for example, com.example.android.testing.mysample.suite ).

The following example shows how to implement a UnitTestSuite test suite named, which is grouped and CalculatorInstrumentationTest CalculatorAddParameterizedTest run together with the test class.

import com.example.android.testing.mysample.CalculatorAddParameterizedTest;import com.example.android.testing.mysample.CalculatorInstrumentationTest;import org.junit.runner.RunWith;import org.junit.runners.Suite;// Runs all unit tests.@RunWith(Suite.class)@Suite.SuiteClasses({CalculatorInstrumentationTest.class,        CalculatorAddParameterizedTest.class})public class UnitTestSuite {}
Running instrumented unit tests

To run the instrumented test, follow these steps:

1. Make sure your project is synchronized with gradle by clicking Sync Project in the toolbar.

2. Run the test in one of the following ways:

    • To run a single test, open the Project window, and then click Run.
    • To test all methods in a class, right-click the class or method in the test file, and then click Run.
    • To run all tests in the catalog, right-click the directory and select Run Tests.

Gradle's Android plugin compiles the test code located in the default directory (src/androidtest/java/), builds the test apk and production apk, installs two apk on the connected real machine or emulator, and runs the test. Android Studio then displays the results of the test execution in the Run window.

Note: When you run or debug a test tool, Android Studio does not inject the extra methods needed for instant running and turns off the feature.

Run tests using the Firebase test lab

Slightly....

(Please check the original text)

Additional Sample Code

To download to the sample application, see Android Activityinstrumentation Sample.

Android Test (v): instrumented unit Test

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.