1. Configure the project to support unit testing
Before writing the test, let's make a simple check to make sure the project is properly configured.
First, verify that "Unit Tests" is selected in the Test Artifact in the Build variants window.
Then, src
Create and folder within the project's folder test
test/java
. It is important to note that you cannot do this in Android view, either in the file manager of the system, or in the top left of the Project window by clicking the drop-down menu to select Project view. The final engineering structure should look like this:
(in the remainder of Codelab, you can return to continue using Android drawing view)
Finally, open the project build.gradle(Module:app)
file, add JUnit4 dependencies, and click on the Gradle sync button.
Build.gradle
dependencies { ‘libs‘, include: [‘*.jar‘]) ‘com.android.support:appcompat-v7:22.1.1‘ test‘junit:junit:4.12‘}
When you synchronize the Gradle configuration, you may need to download JUnit dependencies on the Internet.
In addition, when you create a new project, a lot of dependencies already have, you can actually not add.
2. Create a first unit test
Now, everything is ready, so let's start writing the first Test. First, create a very simple class to be tested: the Calculator class.
Then, add some basic arithmetic operations to the class, such as addition and subtraction. Copy the following code into the editor. Do not worry about the actual implementation, temporarily let all the methods return 0.
Calculator.java
Package com.example.testing.testingexample; Public classCalculator {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 quick way to create test classes. Simply right-click the Calculator class declaration in the editor, select Go to > Test, and then "Create a new test ..."
In the dialog window that opens, select JUnit4 and "setup/@Before" and generate test methods for all calculator operations.
In this way, the test class framework is generated in the correct folder (app/src/test/java/com/example/testing/testingexample)
, and the test method is populated within the framework. Here is an example:
Calculator.java
Package Com.example.testing.testingexample;import Org.junit.before;import Org.junit.test;importStaticorg.junit.assert.*; Public classcalculatortest {PrivateCalculator Mcalculator; @before public void setUp() throws Exception{Mcalculator =NewCalculator (); } @Test public void testsum() throws Exception{//expected:6, Sum of 1 and 5Assertequals (6D, Mcalculator.sum (1D5D),0); } @Test public void testsubstract() throws Exception{Assertequals (1D, Mcalculator.substract (5D4D),0); } @Test public void testdivide() throws Exception{Assertequals (4D, Mcalculator.divide ( -D5D),0); } @Test public void testmultiply() throws Exception{Assertequals (TenD, Mcalculator.multiply (2D5D),0); }}
Either copy the code to the editor or use the assertions provided by the JUnit framework to write your own tests.
3. Run unit Tests
Finally it's time to run the test! Right-click on CalculatorTest
the class and select Run > Calculatortest. You can also run tests from the command line and enter them in the project directory:
test
Regardless of running the test, you should see that the output shows that 4 tests failed. This is the expected result because we have not yet implemented the operation.
Let's modify the methods in the Calculator class to sum(double a, double b)
return a correct result and rerun the test. You should see 3 of the 4 tests fail.
Calculator.java
public double sum(double a, double b){ return a + b;}
As an exercise, you can implement the remaining methods to make all the tests pass.
You may have noticed that Android studio never lets you connect to a device or launch a simulator to run tests. That's because the src/tests
tests in the directory are unit tests that run on the local computer's Java virtual machine. Write tests, implement features to make tests pass, and then add more tests ... This way of working makes fast iterations possible, which we call test-driven development .
It is important to note that when you run the test locally, Gradle provides you with an Android.jar package that contains the Android framework in the environment variables. But they are functionally incomplete (so, for example, you can't simply invoke Activity
the method and expect them to take effect). It is recommended to use the mocking framework such as Mockito to mock any Android method you need to use. For tests that run on the device and take full advantage of the Android framework, continue to the next section of this tutorial.
4. Configure the project to support instrumentation testing
While running instrumentation testing is supported within the Android framework, the current development focus is focused on the new, just released as part of the Android testing support Library AndroidJUnitRunner
. The test library contains Espresso, a framework for running functional UI tests. Let's build.gradle
add them to our project by editing the relevant sections.
Build.gradle
Apply plugin:' Com.android.application 'Android {Compilesdkversion ABuildtoolsversion"22.0.1"Defaultconfig {ApplicationID"Com.example.testing.testingexample"Minsdkversion theTargetsdkversion AVersioncode1Versionname"1.0" //add This line:Testinstrumentationrunner"Android.support.test.runner.AndroidJUnitRunner"} buildtypes {release {minifyenabledfalseProguardfiles 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.0Testcompile' 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 some dependent version conflicts, you need to make sure that com.android.support:appcompat-v7
the version number of the library is the 22.0.0
same as the code snippet above.
Also, Android Studio may remind you that you Build Tools 22.0.1
are not installed. You should accept the repair suggestions, and studio will install build tools for you or modify the line in Build.gradle to the version already installed on your computer.
After the above work is done, switch to Android instrumentation Testsin the Build variants window and your project should sync automatically. If not, click the Gradle Sync button.
5. Add a simple interaction to the app
Before using espresso for UI testing, let's add some views and simple interactions to the app. We use a user can enter the name of the EditText, welcome the user's button and for the output of the TextView. Open res/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 "> <TextViewandroid: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 "/> <buttonandroid:layout_width="Match_parent"android:layout_height= "Wrap_content" Android:text="Say hello!" Android:layout_below="@+id/edittext"android:onclick="SayHello"/> </relativelayout>
You also need to MainActivity.java
add the onclick handler in:
Mainactivity.java
public void sayHello(View v){ TextView textView = (TextView) findViewById(R.id.textView); EditText editText = (EditText) findViewById(R.id.editText); textView.setText("Hello, ""!");}
You can now run the app and make sure everything works fine. Before clicking the Run button, make sure that your run Configuration is not set to run the test. To change, click the dropdown option and select app.
6. Create and run the espresso test
On the overall view of the project, find the androidTest
package name ending with a () suffix and create a new Java class. You can name it MainActivityInstrumentationTest
, paste the following code in the past.
* * Mainactivityinstrumentationtest.java
Package com.example.testing.testingexample;ImportAndroid.support.test.InstrumentationRegistry;ImportAndroid.support.test.espresso.action.ViewActions;ImportAndroid.support.test.rule.ActivityTestRule;ImportANDROID.SUPPORT.TEST.RUNNER.ANDROIDJUNIT4;ImportAndroid.test.ActivityInstrumentationTestCase2;ImportAndroid.test.suitebuilder.annotation.LargeTest;ImportOrg.junit.After;ImportOrg.junit.Before;ImportOrg.junit.Rule;ImportOrg.junit.Test;ImportOrg.junit.runner.RunWith;ImportStatic Android.support.test.espresso.Espresso.onView;ImportStatic Android.support.test.espresso.action.ViewActions.click;ImportStatic Android.support.test.espresso.action.ViewActions.closeSoftKeyboard;ImportStatic Android.support.test.espresso.action.ViewActions.typeText;ImportStatic android.support.test.espresso.assertion.ViewAssertions.matches;ImportStatic android.support.test.espresso.matcher.ViewMatchers.withId;Importstatic android.support.test.espresso.matcher.ViewMatchers.withText; @RunWith (Androidjunit4.class) @ Largetestpublic class mainactivityinstrumentationtest {private static finalStringstring_to_be_typed ="Peter"; @Rule public activitytestrule<mainactivity> Mactivityrule =NewActivitytestrule<> (Mainactivity.class); @Test PublicvoidSayHello () {Onview (Withid (R.id.edittext)). Perform (TypeText (string_to_be_typed), Closesoftkeyboard ());//line 1Onview (Withtext ("Say hello!"). Perform (click ());//line 2 StringExpectedtext ="Hello,"+ string_to_be_typed +"!"; Onview (Withid (R.id.textview)). Check (Matches (Withtext (Expectedtext)));//line 3}}
The test class runs through Androidjunitrunner and executes the sayHello()
method. Here's what to do on a line-by-row basis:
- 1. First, find the ID
editText
of the view, enter Peter
, and then close the keyboard;
- 2. Next, click on
Say hello!
The view, we do not set the ID in the layout of the XML for this button, therefore, by searching the text above it to find it;
- 3. Finally, the
TextView
text above is compared with the expected results, and if so, the test is passed;
You can also right click on the domain name to run the test, select run>mainactivityinstrume ... (the second one with Android icon)
This will run the test on the simulator or connected device, and you can see the actions performed on the phone screen (for example, EditText
typing). The final pass and failed test results will be output in Android studio.
Unit testing and UI testing in Android Studio