Android Open source test framework Learning

Source: Internet
Author: User

Recently, due to work needs, analysis of some Android testing framework, in this also shared the finished data.

Android testing is roughly divided into three chunks:

    1. Code Layer Testing
    2. User operation simulation, functional testing
    3. Installation deployment and stability testing
Code Layer Testing

For generic Java code, with traditional JUnit testing, developers often write white-box test code for important interfaces and functions without much discussion.

But because of the special operating mechanism of Android (Dalvik virtual machine), there are special components such as application, Activity, service and so on, and these components all involve the problem of life cycle management.

To test these components, Google offers a set of targeted testing frameworks that Androidtestframework

Official Tutorials Link http://developer.android.com/training/testing.html

Official API Http://developer.android.com/reference/android/test/package-summary.html

One of the most commonly used is the activity test, the Activityinstrumentationtestcase2<t> class.

Inheriting this class allows you to get a mock object of activity through the getactivity () method, which enables testing of various interface elements. The code is as follows

public class Loginactivitytest extends activityinstrumentationtestcase2<loginactivity> {        Loginactivitytest mactivity;        Button Btnlogin;        Public Loginactivitytest () {      super (Loginactivity.class);//must implement Super (TestClass)        }        @Override    protected void SetUp () throws Exception {        super.setup ();        Mactivity = Getactivity ();                Btnlogin = Mactivity.findviewbyid (R.id.btnlogin);    }        public void Testgetactivity () {           assertnotnull ("Can ' t get loginactivity", mactivity);           Assertnotnull ("Can ' t get Loginbutton", btnlogin);        }}

It is important to note that the thread that the test code runs on is not the UI thread. So if you need to do something like SetText or click on a UI element, you need to do it through the getactivity (). Runonuithread (Action) method. The code is as follows

Getactivity (). Runonuithread (New Runnable () {            @Override public            void Run () {                 btnlogin.click ();            }        );
User operation simulation, functional testing

Although Androidtestframework can help us to complete the testing of various interfaces. However, this code is very tedious to write. And in most cases, what we need is a coherent business process test that has jumps between multiple activities. This test is closer to the traditional white-box test, and only operates on visible UI elements, simulating the user's behavior to complete the test.

Google also provides us with a set of test scenarios specifically for UI elements that are visible http://developer.android.com/tools/testing/testing_ui.html

But Google's UI framework is still not very friendly. To this end, I have looked for some relatively mature testing frameworks to help us. After a series of analytical comparisons and actual code tests, it is recommended to use the Robotium Open source framework as the main business testing framework for a period of time.

Robotium Introduction

Robotium is a foreign Android Automation testing framework, mainly for Android platform applications for black box Automation testing, it provides simulation of various gesture operations (click, Long Press, swipe, etc.), find and assert the mechanism of the API, to be able to manipulate the various controls. Robotium combines Android's official testing framework to automate the testing of applications. In addition, the Robotium 4.0 version already supports the operation of the WebView. Robotium is supportive of Activity,dialog,toast,menu.

Source and related information address: https://code.google.com/p/robotium/

Robotium has a clear method of invocation, good compatibility, complete documentation and a large number of practical applications, and supports screenshots. Best fit for our current real needs. Actual testing allows the Jenkins system to be compatible without special configuration.
The following is an example of the actual test code in a HSA project. The test case completes a process from login, menu selection, to input validation to the function interface.

public class Loginactivitytest extends activityinstrumentationtestcase2<loginactivity> {solo solo;        Loginactivity mactivity;    Public Loginactivitytest () {super (Loginactivity.class);        } @Override protected void SetUp () throws Exception {Super.setup (); Mactivity = Getactivity ();//initial loginactivity solo = new solo (Getinstrumentation (), mactivity);//main entrance of the initial Robotium, solo on        like} public void Testlogin () {//clear user name EditText content solo.clearedittext (0);                Enter "UserName" to username EditText solo.entertext (0, "userName");        Clear Password EditText content Solo.clearedittext (1);                Enter "Userpass" to Password EditText solo.entertext (1, "Userpass");        Clear site EditText content Solo.clearedittext (2);                Enter "SiteCode" to Site EditText solo.entertext (2, "SiteCode");                Click the login button Solo.clickonbutton ("Login"); Verify that the current interface is Mainlistactivity solo.assertcurrentactivity ("ExpecteD mainlistactivity Activity "," mainlistactivity ");        Click the first item in the dynamic menu list to go to the Next Level submenu interface Solo.clickinlist (0);                Verify that the current interface is submenuactivity solo.assertcurrentactivity ("Expected submenuactivity activity", "submenuactivity");        Click the first item in the submenu list to enter the function interface solo.clickinlist (0);                Verify that the current interface is receiveactivity solo.assertcurrentactivity ("Expected receiveactivity activity", "receiveactivity");        Click the "Use Current people" button in the interface Solo.clickonbutton ("Use current person");                Input weight solo.entertext (1, "123");                Enter the number Solo.entertext (2, "21123456798");            Simulates the soft keyboard, sending the EditText Action_done event solo.getcurrentactivity (). Runonuithread (New Runnable () {@Override            public void Run () {Solo.getedittext (2). Oneditoraction (Editorinfo.ime_action_done);                }        }); Looking for a textview that has "scanned 1", automatically waits 10 seconds for a Boolean succ = Solo.searchtext ("1 scanned"))//Gong Asserttrue (SUCC); }}

As you can see, Robotium uses a solo object to simulate various events, the code is clear and understandable, and is fully compatible with native Androidtestframework

Installation deployment and stability testing

One of the most notorious problems with Android is fragmentation, which is more pronounced in China. In general, the 2.3.X and 4.x systems accounted for half of the total, in addition to the existence of a large number of cottage customization system.

So in this recommended two cloud testing tools, Testin and Baidu cloud testing.

Two frame test is very simple, after registering an account on the website to upload the APK, the site will be a large number of real-machine installation and monkey testing. After the test is completed, a test is sent to the registered mailbox.

Testin supports the code testing of the Robotium framework while uploading the project APK and test apk (same signature).

Testin Address: http://www.testin.cn/

Baidu Cloud Test: http://mtc.baidu.com/

Other Test Framework Monkey testing

The Android SDK Development Kit comes with a monkeyrunner tool that can be used for monkey testing.
Document Address:

    • Http://developer.android.com/tools/help/monkeyrunner_concepts.html
    • Http://developer.android.com/tools/help/monkey.html
Robolectric

A JVM-based Android test framework, the biggest feature is that you do not need to start the emulator, so very fast!
Most of the native SDK features are currently supported for testing and support for resource, but there is still a shortage of simulations on some special hardware. Looking forward to further improvement
Example code:

Test class for Myactivity@runwith (robolectrictestrunner.class) public class Myactivitytest {  @Test  public void Clickingbutton_shouldchangeresultsviewtext () throws Exception {    activity activity = Robolectric.buildactivity (Myactivity.class). Create (). get ();    Button Pressmebutton = (button) Activity.findviewbyid (R.id.press_me_button);    TextView results = (TextView) Activity.findviewbyid (R.id.results_text_view);    Pressmebutton.performclick ();    String Resultstext = Results.gettext (). toString ();    Assertthat (Resultstext, Equalto ("Testing Android rocks!"));}  }

Address: http://robolectric.org/index.html

Google Espresso

Google opens a test framework for open source in October 2013. It is said that the actual validation of multiple projects has been done within Google and may be added to the default ANDROIDSDK in the future.
Designed to be close to robotium, mainly used for business end simulation behavior testing. Compared with Robotium, it has more powerful UI elements to match the search function and faster running speed.
However, after my actual use, found that the framework of code writing is relatively complex, far less light than the robotium. In addition, the framework can not be run in the default androidtestframework (can be considered as an upgrade version), and because just open source, missing documents and application cases and other materials, resulting in a relatively inefficient test code writing, it is temporarily not used.
Address: Https://code.google.com/p/android-test-kit/wiki/Espresso

Mockito

A mainstream framework for mock testing
Address: https://code.google.com/p/mockito/

  List mockedlist = mock (list.class);  When (Mockedlist.get (0)). Thenreturn ("first");  System.out.println (mockedlist.get (0));
Summarize

Without surprises, the Android project will build a test framework for the next period of time using the following scenario:

    • Code level: Androidtestframework + Junit
    • UI Business Simulation: Robotium
    • Installation deployment: Testin
    • Ci:jenkins

Interested students can also pay attention to the progress of the two frameworks of robolectric and espresso.

Category: Android

Android Open source test framework Learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.