Unit Test and UI test in Android Studio, androidui
This tutorial is translated from codelab for Testing in Google I/O 2015. If you are familiar with scientific Internet access, click here to read: Unit and UI Testing in Android Studio. Limited capability. If any translation error occurs, please correct your criticism. If you need to reprint it, please indicate the source.
Download test source code from Github
Directory
- Unit Test and UI test in Android Studio-1. Overview
- Perform unit test and UI test in Android Studio-2. Create a new Android Studio Project
- Unit Test and UI test in Android Studio-3. configure a project that supports unit test
- Unit Test and UI test in Android Studio-4. Create the first unit test
- Unit Test and UI test in Android Studio-5. Run unit test
- Unit Test and UI test in Android Studio-6. configure a project that supports the Instrumentation Test
- Unit Test and UI test in Android Studio-7. Add simple interaction for the app
- Perform unit test and UI test in Android Studio-8. Create and run Espresso Test
- Unit Test and UI test in Android Studio-9. Congratulations!
1. Overview
In this codelab, you will learn how to configure projects for testing in Android Studio, write and run unit tests on development machines, and how to perform functional UI tests on mobile phones.
What will you learn
- Update the Gradle build file containing JUnit and Android Testing Support Library
- Compile a unit test running on the local Java Virtual Machine
- Compile an Espresso test running on a mobile phone or virtual machine
What do you need
- Android Studio v1.2 +
- Android 4.0 + Testing Devices
2. Create a new Android Studio Project
If Android Studio is started for the first time, select"Start a new Android Studio project". If you have already opened a project, selectFile> New Project...
"Create new projectThe Wizard will guide the entire process and enter the following content on the first page:
Setting |
Value |
Application Name |
TestingExample |
Company demain |
Testing.example.com |
This ensures that your code has the same name as the content explained by codelab. All other options are set as default.NextUntil the project is created.
ClickRunClick to check whether the app is running normally. Either select a boot device from the simulator list or confirm that the device in debug mode is correctly connected to the computer through USB.
The app has not done anything at present, but the screen should display "Hello world !" And app name.
Frequently Asked Questions
- How to install Android Studio?
- How To Enable USB debugging?
- Why can't Android Studio find my device?
- Android error: Unable to install *. apk to the device: timeout?
3. configure a project that supports Unit Testing
Before writing a test, let's make a simple check to ensure that the project configuration is correct.
First, confirmBuild VariantsIn the windowTest ArtifactUnit Tests is selected ".
Thensrc
Folder creationtest
Andtest/java
Folder. Note that you cannotAndroidView, or create in the System File Manager, or click the drop-down menu in the upper-left corner of the Project window to selectProjectView. The final project structure should be as follows:
(In the remaining part of codelab, you can continue usingAndroidProject view)
Finally, openbuild.gradle(Module:app)
File, add the JUnit4 dependency, and clickGradle syncButton.
Build. gradle
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.1.1' testCompile 'junit:junit:4.12'}
When you synchronize Gradle configurations, you may need to download JUnit dependencies online.
4. Create the first unit test
Now, everything is ready. Let's start writing the first test. First, create a very simple tested class: Calculator class.
Then, add some basic arithmetic operations to the class, such as addition and subtraction. Copy the following code to the editor. Don't worry about the actual implementation. Temporarily let all methods return 0.
Calculator. java
package com.example.testing.testingexample;public class Calculator { public double sum(double a, double b){ return 0; } public double substract(double a, double b){ return 0; } public double divide(double a, double b){ return 0; } public double multiply(double a, double b){ return 0; }}
Android Studio provides a method to quickly create a test class. Right-click the Calculator class declaration in the editor and selectGo to> Test, And then"Create a new test... "
In the displayed dialog box, selectJUnit4And"SetUp/@ Before", And generate a test method for all calculator operations.
In this way, it will be in the correct folder(app/src/test/java/com/example/testing/testingexample)
Generate a test framework and enter the test method in the framework. The following is an example:
Calculator. java
package com.example.testing.testingexample;import org.junit.Before;import org.junit.Test;import static org.junit.Assert.*;public class CalculatorTest { private Calculator mCalculator; @Before public void setUp() throws Exception { mCalculator = new Calculator(); } @Test public void testSum() throws Exception { //expected: 6, sum of 1 and 5 assertEquals(6d, mCalculator.sum(1d, 5d), 0); } @Test public void testSubstract() throws Exception { assertEquals(1d, mCalculator.substract(5d, 4d), 0); } @Test public void testDivide() throws Exception { assertEquals(4d, mCalculator.divide(20d, 5d), 0); } @Test public void testMultiply() throws Exception { assertEquals(10d, mCalculator.multiply(2d, 5d), 0); }}
Copy the code to the editor or use the assertions provided by the JUnit framework to write your own tests.
5. Run the unit test
It's time to run the test! Right-clickCalculatorTest
Class, selectRun> CalculatorTest. You can also run the test through the command line and enter the following in the project directory:
./gradlew test
No matter how you run the test, you should see that the output shows that all four tests have failed. This is the expected result, because we have not implemented any operation.
Let's modifysum(double a, double b)
Method returns a correct result and re-runs the test. You should see that three of the four tests failed.
Calculator. java
public double sum(double a, double b){ return a + b;}
As an exercise, you can implement the remaining methods to pass all tests.
You may have noticed that Android Studio never allows you to connect to a device or start a simulator to run the test. That's becausesrc/tests
The test in the directory is a unit test running on the Local Computer Java virtual machine. Compile the test, implement the function to pass the test, and then add more tests... this way of working makes quick iteration possible, which is calledTest-driven development.
It is worth noting that when you run the test locally, Gradle provides an Android. jar package containing the android framework in your environment variables. However, they are not fully functional (So, for example, you cannot simply callActivity
And expect them to take effect ). We recommend that you use Mockito and other mocking frameworks to mock any Android method you need. For tests that run on devices and make full use of the Android framework, continue to the next part of this tutorial.
6. Configure the project supporting the Instrumentation Test
Although it supports running the instrumentation Test in the Android framework, the current development focus is mainly on the newly releasedAndroid Testing Support LibraryPart of the newAndroidJUnitRunner
. Test Library inclusionEspressoFramework used to run functional UI testing. Let's Editbuild.gradle
To add them to our project.
Build. gradle
apply plugin: 'com.android.application'android { compileSdkVersion 22 buildToolsVersion "22.0.1" defaultConfig { applicationId "com.example.testing.testingexample" minSdkVersion 15 targetSdkVersion 22 versionCode 1 versionName "1.0" //ADD THIS LINE: testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } //ADD THESE LINES: packagingOptions { exclude 'LICENSE.txt' }}dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.0.0' //← MAKE SURE IT’S 22.0.0 testCompile 'junit:junit:4.12' //ADD THESE LINES: androidTestCompile 'com.android.support.test:runner:0.2' androidTestCompile 'com.android.support.test:rules:0.2' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.1'}
Important: Due to dependency version conflicts, you need to confirmcom.android.support:appcompat-v7
The database version is22.0.0
, Like the code snippet above.
In addition, Android Studio may remind youBuild Tools 22.0.1
Not installed. You should accept the repair suggestions. Studio will install Build Tools for you or change this line to a version that has been installed on your computer in build. gradle.
After the above work is completedBuild VariantsSwitch window innerAndroid Instrumentation Tests, Your project should be automatically synchronized. If no, clickGradle syncButton.
7. Add simple interaction for the app
Before using Espresso for UI testing, let's add some Views and simple interactions for the app. A user can enter the EditText name. Welcome to the user's Button and TextView for output. Openres/layout/activity_main.xml
Paste the following code:
Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:hint="Enter your name here" android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textView"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Say hello!" android:layout_below="@+id/editText" android:onClick="sayHello"/></RelativeLayout>
You also needMainActivity.java
Add onClick handler:
MainActivity. java
public void sayHello(View v){ TextView textView = (TextView) findViewById(R.id.textView); EditText editText = (EditText) findViewById(R.id.editText); textView.setText("Hello, " + editText.getText().toString() + "!");}
Now you can run the app and make sure everything works properly. ClickRunBefore the button, confirm yourRun ConfigurationNot set to run the test. To change the value, click the drop-down list and selectApp.
8. Create and run the Espresso Test
In the overall project view, find (androidTest
) And create a new Java class. You can name itMainActivityInstrumentationTest
Paste the following code.
** MainActivityInstrumentationTest. java
package com.example.testing.testingexample;import android.support.test.InstrumentationRegistry;import android.support.test.espresso.action.ViewActions;import android.support.test.rule.ActivityTestRule;import android.support.test.runner.AndroidJUnit4;import android.test.ActivityInstrumentationTestCase2;import android.test.suitebuilder.annotation.LargeTest;import org.junit.After;import org.junit.Before;import org.junit.Rule;import org.junit.Test;import org.junit.runner.RunWith;import static android.support.test.espresso.Espresso.onView;import static android.support.test.espresso.action.ViewActions.click;import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;import static android.support.test.espresso.action.ViewActions.typeText;import static android.support.test.espresso.assertion.ViewAssertions.matches;import static android.support.test.espresso.matcher.ViewMatchers.withId;import static android.support.test.espresso.matcher.ViewMatchers.withText;@RunWith(AndroidJUnit4.class)@LargeTestpublic class MainActivityInstrumentationTest { private static final String STRING_TO_BE_TYPED = "Peter"; @Rule public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>( MainActivity.class); @Test public void sayHello(){ onView(withId(R.id.editText)).perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard()); //line 1 onView(withText("Say hello!")).perform(click()); //line 2 String expectedText = "Hello, " + STRING_TO_BE_TYPED + "!"; onView(withId(R.id.textView)).check(matches(withText(expectedText))); //line 3 }}
Test class passedAndroidJUnitRunnerRun and runsayHello()
Method. Next we will explain what has been done by line:
- 1. First, find
editText
View, inputPeter
And then close the keyboard;
- 2. Next, click
Say hello!
We didn't set the id for this Button in the layout XML. Therefore, we can find it by searching the text above it;
- 3. Finally
TextView
The text above is compared with the expected results. If they are consistent, the test passes;
You can also right-click the domain name to run the test and chooseRun> mainactivityreceivume...(The second one with the Android icon)
In this way, you can run the test on the simulator or connected device. You can view the executed action (for exampleEditText
). Finally, the test results that pass and fail will be output in Android Studio.
Download test source code from Github
9. Congratulations
We hope you will like this tutorial and start testing your application. Then you can learn the following: