Before say then the text, let's talk about the meaning of the Android Unit test or why do we have to do the Android unit test?
Why unit Testing?
Unit tests can help our programmers eliminate bugs in their infancy and reduce time for subsequent integration testing. You can look at this article and probably convince you: why bother with unit testing?
If that article is not convincing you, then I can only use the Killer ~ ~
You can go to the major recruitment sites to see, most companies require developers to write test cases or use frameworks or tools to test, and large companies require more.
Is there anything else you can say? Unit testing is a hard requirement, even if you don't like unit testing, but if you want to get into an ideal company, this is a necessary skill, so anyway you have to learn, anyway, more than the pressure of the body.
So, if you want to learn unit testing, where to find learning resources?
- Android website (https://developer.android.com/training/testing/start/index.html)
- Chinese translation of the official website, this is a series of articles, but also add the author's own views
- A complete set of tutorials on espresso on the Android website
- You can also read my article to get started
But either way, the main word is unit testing through the espresso framework.
Of course there are other test frameworks that you can try, but the espresso framework is a set of testing frameworks that Google has officially recommended, so learn anyway. In addition, since the Android Studio2.2 version, Google has built a graphical interface for the espresso framework to automatically generate unit test code. In the next article, I'll show you how to write unit test code using this graphical interface.
The following officially begins
The first step is to integrate the espresso test environment, which is very simple, add the following two dependencies in the Gradle of the module you want to test:
‘junit:junit:4.12‘‘com.android.support.test.espresso:espresso-core:2.2.2‘, { group‘com.android.support‘‘support-annotations‘ }
The first is JUnit dependency, which is typically configured by default on Android studio, so you only need to configure a second dependency.
Give me a chestnut:
@RunWith ( Androidjunit4.class) @LargeTest public Span class= "Hljs-class" >class Mainactivityinstrumentationtest { @Rule public activitytestrule mactivityrule = new ActivityTestRule <> (Mainactivity.class); @Test public void sayhello () {Onview (Withtext ()). Perform (click ()); Onview (Withid (R.id.textview)). Check (Matches (Withtext ())); }}
The above code is on the Android official website above, about the principle of espresso I will not say, I also can not speak, forcibly speaking, also speak too superficial. To understand the principle of the can go to Google.
So let's focus on two annotations first:
@Rule:
As the name implies, the test rule, the official explanation is that you can refer to a rule or define a method under the annotation, and you are referring to or defining a test rule, which may not be very clear, you can see the note below the sentence:
publicnew ActivityTestRule<>( MainActivity.class);
This sentence defines a test rule, you can see the constructor method of the parameters specified a mainactivity.class, the concrete embodiment is when you run the test code, the app will open directly The Mainactivity interface then carries out the test cases that you define. So when you want to test an interface directly, you can put that interface into this parameter, so that you directly open the interface you specified to test.
@Test:
This annotation is used to define a test case, and when your test class runs, the code that executes is the test annotation (espresso also provides some other annotations, such as: @After, @Before, etc., the specific usage can go to the Android website I wrote above to view), Of course, the above code corresponds to the SayHello test method, the SayHello method is defined as the content to be tested, the meaning of the content is:
onView(withText("Say hello!")).perform(click());
Meaning: According to the text "Say hello!" Find this control and then execute the control's click Method.
onView(withId(R.id.textView)).check(matches(withText("Hello, World!")));
Meaning: Find this control based on the ID "TextView" and then check that the text shown above is "Hello, world!".
Is it easy to understand? Very semantically, generally can read. Espresso also provides other methods for us to call when testing, and some of the common ones are listed below.
But before enumerating the usual methods, you need to explain some of the espresso considerations, or else you will be espresso by the mistakes you make when you test!!!
- either by Withid () or by Withtext () to find controls or other ways such as Withclassname (), Withresourcename (), Withtagkey () , Be sure to ensure that the control you are looking for does exist and is visible on the current page, otherwise it will report: Nomatchingviewexception, of course, you may encounter other anomalies, such as ambiguousviewmatcherexception, Appnotidleexception abnormal and so on, the specific cause of the error can be viewed on the Android website, the address is as follows: Espresso of various anomalies
- If you want to test adapterview, such as a ListView or GridView, using the Onview () method above is not valid because the Adapterview layout item is dynamically rendered and cannot be specified directly, So when you want to test the Adapterview, replace the Onview () method with the OnData () method, similar to the Onview () method return viewinteraction, OnData () method returns Datainteraction, The use of both is basically the same.
Perform () parameters commonly used in the method:
In the above section of the official website code, we use the Perform (click ()), then the addition of the Click () method There are other powerful methods for us to use, the following list some common methods:
- Click ():
Return a click Action,espresso Use this method to perform a single click, just as we manually click the button, just espresso Click this operation to automate the , the following methods are the same reason, will not repeat it.
- cleartext ():
Returns an action that clears the text in the specified view, and uses more than one when testing edittext
- swipeleft ():
Returns a right-to-left action, which is especially useful when testing Viewpager
- swiperight ():
Returns an action that slides from left to right , which is especially useful when testing Viewpager
- swipedown ():
Returns an action
- swipeup () that slides from top to bottom:
Returns a bottom-up action
- Closesoftkeyboard ():
Returns an action that closes the input keyboard
- pressback ():
Returns an action that clicks the return key on the phone
- DoubleClick ():
Returns a double-click action
- Longclick ():
Returns a long press action
- scrollTo ():
Returns a move action
- replacetext ():
Returns an alternate text action
- openlinkwithtext ():
Returns an open specified link action
In addition to the above common methods there are some other less common, want to continue to study can see the Viewactions class in espresso, it should be noted that all the methods include above and not mentioned, there is a prerequisite, The view you want to perform must be displayed on the current screen, which has two meanings:
1, the current interface must be able to find this control
2, this control must be visible
This is a common requirement for all of the above methods, but there are some additional requirements, such as the need to get focus first, etc.
Speaking of which, let's comb what we've learned:
1, how to find specific controls based on ID or text or other methods
2, how to get this control to perform related operations
3, some precautions to use
So now we can completely write a complete test case ourselves.
Let's start with a GIF diagram:
The process of the above dynamic diagram test is: Open the software, swipe viewpager 3 pages, on the last page click the Start Experience button to enter the main interface, click on the appointment to call the car, because there is no login so will jump to the landing page, enter the phone number, and then click Get Verification Code button, and then enter the verification code, Last Click Login.
The code test code for the entire process is as follows:
@LargeTest@RunWith(Androidjunit4.class) Public class startactivitytest { @Rule PublicActivitytestrule<startactivity> Mactivitytestrule =NewActivitytestrule<> (Startactivity.class);@Test Public void startactivitytest() {//Find the Viewpager page by ID and determine if it is visibleViewinteraction Appcompatviewpager = Onview (AllOf (Withid (R.id.viewpager), isdisplayed ()));//Swipe left Viewpager page, the following 3 sentences can also be written in a sentence, espresso will be executed from left to right //Appcompatviewpager.perform (Swipeleft (), Swipeleft (), swipeleft ());Appcompatviewpager.perform (Swipeleft ()); Appcompatviewpager.perform (Swipeleft ()); Appcompatviewpager.perform (Swipeleft ());//Find the "Start experience" button based on the text and determine if it is visibleViewinteraction Appcompatbutton = Onview (AllOf (Withtext ("Start Experience"), isdisplayed ());//Perform button click actionAppcompatbutton.perform (click ());//Locate the control based on the ID of the control and the control's parent layout ID, and determine if it is visibleViewinteraction Appcompatimageview = Onview (AllOf (Withid (R.id.appointmentcallcar), Withparent (WithId (R.id). callcarlayout)), isdisplayed ()));//Execute the control's click actionAppcompatimageview.perform (click ());//Find the control by ID and determine if it is visibleViewinteraction Appcompatedittext = Onview (AllOf (Withid (R.id.phonenumber), isdisplayed ()));//Perform alternate text operation, just plain text input, close input keyboard when finishedAppcompatedittext.perform (ReplaceText ("18894001263"), Closesoftkeyboard ());//Find control based on ID and displayed text content, and determine if visibleViewinteraction AppCompatButton2 = Onview (AllOf (Withid (R.id.getpassword), Withtext ("Get Verification Code"), isdisplayed ());//Execute the control's click actionAppcompatbutton2.perform (click ());//Find the control by ID and determine if it is visibleViewinteraction appCompatEditText2 = Onview (AllOf (Withid (R.id.password), isdisplayed ()));//Perform alternate text operation, just plain text input, close input keyboard when finishedAppcompatedittext2.perform (ReplaceText ("2454"), Closesoftkeyboard ());//Find control based on ID and displayed text content, and determine if visibleViewinteraction AppCompatButton3 = Onview (AllOf (Withid (R.id.login), Withtext ("Login"), isdisplayed ());//Execute the control's click actionAppcompatbutton3.perform (click ()); }}
It is also important to note that when all the test cases have been executed, espresso will automatically close the interface, according to the motion diagram can also be seen, when the login button is finished, and then back to the System screen interface.
When the test is complete, the test results can be seen in the "Run" console of Android studio, such as:
If the test passes smoothly, the all test Passed will be displayed on the left side:
If the test does not pass, the error message is entered in the console on the right, and we can modify our code based on these error messages and then test again.
The above test code only tests the startup and landing functions, you can see that the routines are the same: based on the ID or text and other conditions to find the control, and then perform the control of the related operations, the code is repeated, the only change is to perform the operation and find the condition is not the same, we imagine if the project once very large, We have a manual code to write the test is not very troublesome, and are the same routine, no technical content. If there is a way to automatically generate these test code, and we just need to modify the specific test conditions and not even change these automatically generated code to complete the test, Is it possible to save us a lot of time? And just the Android Studio2.2 version provides a graphical interface for testing using the Espresso framework – theRecord Espresso Test feature that, through this function, We just need to run the software to the real machine or simulator, and then we can just like the usual manual test software, according to business logic click/Swipe, theRecord Espresso test function will automatically generate the corresponding test code, we run the generated test code, Espresso can automatically according to the order we have just done automatic test, is not very convenient ah. about how to use the Record Espresso Test feature, you will write a separate article to illustrate, in fact, the operation is very simple, You can try it yourself first.
Android automated Test--espresso framework use