This article is published in vivo Internet technology wechat public number link: mp.weixin.qq.com/s/-TW7p3z3v… By Zhu Yifei
As a qualified developer, basic development testing ability is essential, development testing can be divided into unit testing and UI testing, through development testing can reduce the self-testing time of developers, improve the quality of development. This article can help junior developers quickly learn about development testing and get started with test coding. This article is also intended for application software junior test engineers to get a quick start coding test cases.
Android 3 minutes to get you started
Before we dive into Android app testing, let’s look at a few concepts.
1, JUnit
JUnit is a unit testing framework for the Java language.
2, Instrumentation,
The framework is based on JUnit, so you can test directly with JUnit. It also provides a test base class for each component of an Android application, so You can also use Instrumentation to test Android components.
Instrumentation and Activity are a little similar, but Activity is the need for an interface, and Instrumentation is not so, we can understand it as a graphical interface, with the ability to start, Utility classes used to monitor other classes (declared with Target Package).
3, Espresso
Automated testing using Android Instrumentation API, these API calls in a different thread running with the UI thread, therefore, the use of automated methods to test the user interface will lead to serious concurrency problems, and then produce inconsistent and unreliable test results. Google’s solution to this problem is Espresso, a testing framework that enables UI tests to run safely in a multi-threaded environment and removes much of the boilerplate code that is required to write tests.
Second, test application
AndroidJUnit is based on JUnit, which enables us to run local unit tests on the JVM as well as instrumented tests on Android devices. The placement of the test code depends on the type of test you are writing. Android Studio provides source directories (source sets) for the following two types of tests:
Local unit tests
- In the module name/SRC/test/Java /.
- These tests are run on the machine’s native Java Virtual Machine (JVM). When your tests have no Android framework dependencies or when you can emulate Android framework dependencies, you can leverage these tests to minimize execution times.
- At run time, these tests are executed on a modified version of Android.jar with all final modifiers removed. That way, you can use common emulation libraries like Mockito.
Instrument test
- In the module name/SRC/androidTest/Java /.
- These tests are run on hardware devices or emulators. These tests have access to the Instrumentation API, allowing you to obtain certain information (such as the Context of the application you are testing), and allowing you to control the application under test through the test code. You can use these tests when writing integration and functional UI tests to automate user interactions, or when testing Android dependencies that mock objects cannot satisfy.
- Because instrument tests are built into APK (separate from your application APK), they must have their own Androidmanifest.xml file. However, because Gradle automatically generates this file at build time, it is not visible in your project source set. You can add your own manifest file when necessary, such as when you need to specify another value for minSdkVersion or register a run listener for testing purposes. When building an application, Gradle merges multiple manifest files into a single manifest.
When you create a new project or add an application module, Android Studio creates the test source sets listed above and adds a sample test file to each set. You can see them in the Project window, as shown in Figure 1-1:
(figure 1-1)
Add a new test
Before writing unit tests, make sure that gradle is configured accordingly. As shown in Figure 1-2:
(FIG. 1-2)
The next formal entry, excited, step by step will be very simple oh ~
1. Create a local unit test
Step 1: Open the Java file that contains the code you want to test. Such as Calculator. Java.
/** * [description] * author: Yifei * created at 17/6/8 12:00 PM */ Public Class Calculator {public double sum(double a, double b){return a + b; } public double substract(double a, double b){ return a - b; } public double divide(double a, double b){ return a * b; } public double multiply(double a, double b){ return a / b; }}Copy the code
Step 2: Click the class or method you want to test, then right click as shown in Figure 2, or press Ctrl+Shift+T (⇧⌘T).
(figure 2)
Select Create Test as shown in Figure 3, setUp/ @before and the method you want to test, and then click OK.
(figure 3)
In the Choose Destination Directory dialog box, click the source set corresponding to the type of test you want to create: androidTest for instrument tests, test for local unit tests. Then click OK. As shown in Figure 4:
(figure 4)
Calculatortest.java appears under module-name/ SRC /test/ Java /.
/** * [description] * author: Yifei * created at 17/6/8 12:01 PM */ public class CalculatorTest {private Calculator mCalculator; @Before public void setUp() throws Exception { mCalculator = new Calculator(); } @Test public void sum() throws Exception { //expected: 6, sum of 1 and 5 assertEquals(6d, mCalculator.sum(1d, 5d), 0); } @Test public void substract() throws Exception { assertEquals(1d, mCalculator.substract(5d, 4d), 0); } @Test public void divide() throws Exception { assertEquals(4d, mCalculator.divide(20d, 5d), 0); } @Test public void multiply() throws Exception { assertEquals(10d, mCalculator.multiply(2d, 5d), 0); }}Copy the code
Select the method name and right – click run’method()’.
(figure 5)
So a local unit test is done, isn’t it easier?
2. Create an Espresso test
Before creating the test, let’s create a testActivity.java to test and add a few simple interactions. Enter any string in EditText and click Button to display it in TextView, as shown in Figures 6 and 7:
(figure 6)
(figure 7)
In order to take care of more friends, write as many details as possible here, the corresponding Activity/XML file is as follows:
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class TestActivity extends AppCompatActivity implements View.OnClickListener { private TextView textView; private EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); init(); } public void init(){ textView = (TextView) findViewById(R.id.textView); editText = (EditText) findViewById(R.id.editText); findViewById(R.id.btnText).setOnClickListener(this); } @Override public void onClick(View view) { int id = view.getId(); if (id == R.id.btnText) { textView.setText("Hello, " + editText.getText().toString() + "!" ); }}}Copy the code
<? The XML version = "1.0" encoding = "utf-8"? > <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.example.testing.androidtest.TestActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <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:id="@+id/btnText" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello world!" android:layout_below="@+id/editText"/> </RelativeLayout> </android.support.design.widget.CoordinatorLayout>Copy the code
With that done, let’s create and run Espresso tests together. In the module name/SRC/androidTest/Java/create TestActivityInstrumentationTest. Java
The test class runs through AndroidJUnitRunner and executes button’s onClick(View) method. Here is a line-by-line explanation of what was done:
- First, find the View with ID editText, type Peter, and close the keyboard;
- Next, click Hello World! View, we can either find a control by its ID or by searching its text;
- Finally, compare the text on TextView with the expected result. If the result is consistent, the test passes.
You can also right click on the domain to Run the test, select Run > TestActivityInstrumentationTest… As shown in Figure 8:
(figure 8)
This will run the test on the emulator or connected device, and you can see the actions being performed (such as typing on EditText) on the phone screen, as shown in the video below.
Finally, pass and fail test results are printed in Android Studio.
(figure 9)
Finally, congratulations. You got the hang of it.