Analysis of unit test and ui test in Android studio
1. 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.
In addition, when you create a new project, many dependencies are available, but you do not need to add them.
2. 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.
3. 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.
4. 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.
5. 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
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.
6. 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
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, input
Peter
2. Click
Say hello!
We didn't set the id for the Button in the layout XML. Therefore, we can find it by searching the text above it; 3. Finally, we will
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.