Basic knowledge about Android 12: Android automated testing 04-robobench: instance (I)

Source: Internet
Author: User

The previous article has a rough introduction to the JUnit-based Android testing framework. Next we will analyze the activity testing.

This article mainly introduces two examples of activity tests based on robotium. One is to test a single activity and the other is to test multiple activities.

1. robotium Overview

First, let's take a look at the android testing class hierarchy:

We can see that the android testing methods mainly include androidtextcase and instrumentationtextcase. In this article, I will introduce the Instrumentation Test method. What is instrumentation?
The instrumentation and activity are a bit similar, but the activity requires an interface, and the instrumentation is not like this. We can understand it as a kind of graphic interface without startup capability, tool class used to monitor other classes (declared using target package.

2. Example of a single activity test

2.1 normal test

I think you will try the noteslist example after installing robotium. This is an example mentioned on the official website.
First open the noteslist source code
\ Samples \ Android-7 \ notepad
Open the noteslisttest source code.
Http://code.google.com/p/robotium/downloads/list/ExampleTestProject_v2.3.zip can be downloaded from above
Make some modifications. Because noteslist was developed in androidv21, and my test code is V23. We 'd better change it to a consistent one.
Modify androidmanifest. xml under noteslisttest
<Uses-SDK Android: minsdkversion = "9"/>
Changed to <uses-SDK Android: minsdkversion = "7"/>
 
What do these two numbers mean?
7 -- androidv21, 9 -- androidv23, the lowest version is 3 -- androidv15.
You will know the version of the number in order.
 
In noteslisttest, right-click Properties -- Android, and select androidv21.
In this way, the android jar in noteslisttest is changed from android2.3 to android2.1.
 
I think it is also important to talk about another configuration.
Still in androidmanifest. xml
<Instrumentation Android: targetpackage = "com. example. Android. Notepad" Android: Name = "android. Test. instrumentationtestrunner"/>
The bold red string indicates the package of the Code to be tested.
 
OK, so we can get the code ready. Run as -- Android JUnit Test
 
Next, let's take a look at the specific code in noteslisttest and see how it is tested.

Private Solo; // inform the system of the public notepadtest () {super ("com. example. android. notepad ", noteslist. class);} // open noteslist public void setup () throws exception {solo = new solo (getinstrumentation (), getactivity ();} @ smoke public void testaddnote () throws exception {solo. clickonmenuitem ("add note"); solo. assertcurrentactivity ("Expected noteeditor activity", "noteeditor"); // assert that noteeditor activity is opened solo. entertext (0, "NOTE 1"); // in text field 0, add Note 1 solo. goback (); // go back solo. clickonmenuitem ("add note"); // clicks on menu item solo. entertext (0, "NOTE 2"); // in text field 0, add note 2 solo. gobacktoactivity ("noteslist"); // go back to first activity named "noteslist" Boolean expected = true; Boolean actual = solo. searchtext ("NOTE 1") & solo. searchtext ("NOTE 2"); assertequals ("NOTE 1 and/or note 2 are not found", expected, actual); // assert that NOTE 1 & Note 2 are found}

This is our first case. The main purpose is to test the function of adding text.
Clickonmenuitem (string)
Click the menu button and select the menu with the text description as string. For example, we use "add note"
Assertcurrentactivity (string message, string name)
This is to determine whether the current activity is consistent with what I expected
Message is a descriptive text.
Name indicates the activity name.
For details about how to know the name of an activity, I have searched for a document for a long time. The current method is to check androidmanifest. xml -- Application label -- Application nodes in the source code, where we can see the name of all the activities.
 
Entertext (INT index, string text)
The index is used to identify the edittext to be written. If only one edittext is opened currently, Index = 0
Text: the content to be written.
 
Goback ()
It is equivalent to the back key on the mobile phone)
 
Gobacktoactivity (string name)
Returns to the specified activity.
 
Searchtext (string text)
Search for text content in the current activity

@Smoke public void testEditNote() throws Exception {solo.clickInList(2); // Clicks on the second list linesolo.setActivityOrientation(Solo.LANDSCAPE); // Change orientation of activitysolo.clickOnMenuItem("Edit title"); // Change titlesolo.enterText(0, " test"); //In first text field (0), add test. solo.goBackToActivity("NotesList");boolean expected = true;boolean actual = solo.searchText("(?i).*?note 1 test"); // (Regexp) case insensitive// insensitiveassertEquals("Note 1 test is not found", expected, actual); //Assert that Note 1 test is found}

The second case mainly tests the editing function
Clickinlist (INT index)
Click the index row of the List table to enter the text interface.
Solo. setactivityorientation (Solo. Landscape );
Setactivityorientation: sets the display mode of the mobile phone screen.
Landscape: horizontal display
Portrait: vertical display

@Smoke public void testRemoveNote() throws Exception { solo.clickOnText("(?i).*?test.*");   //(Regexp) case insensitive/text that contains "test" solo.clickOnMenuItem("Delete");   //Delete Note 1 test boolean expected = false;   //Note 1 test & Note 2 should not be found boolean actual = solo.searchText("Note 1 test"); assertEquals("Note 1 Test is found", expected, actual);  //Assert that Note 1 test is not found solo.clickLongOnText("Note 2"); solo.clickOnText("(?i).*?Delete.*");  //Clicks on Delete in the context menu actual = solo.searchText("Note 2"); assertEquals("Note 2 is found", expected, actual);  //Assert that Note 2 is not found }

The third case is used to test the deletion function.
Clickontext (string text)
Click the place containing the text
Text can be represented by a regular expression.
(? I) ---- case insensitive. It is case sensitive by default.
Regular Expressions are consistent with Java expressions.
 
Clicklongontext (string text)
Hold down selected text for a long time

Note: The tested APK and tested APK must use the same signature.

2.2 data-driven testing

This example and the previous example both test a single activity. The difference is that the test data used in this example comes from the file.

The tested code is a simple calculator with the code:/files/morebetter/android.
Code/androidcalculator.rar

1. Data-Driven Testing Architecture
Test Data source: testdata.csv

First Value Second Value
10 1.5
20 3

The first input box reads data from the first value.
The second input box reads data from second value.
Click multiply
Compare the test results with the expected results and write the results to the file.

2. Create a data source file
Format:
3. upload the data source file to the emulator.
Create the Res/raw/Files folder in the tested code. In this way, the Files folder can be uploaded to emulator.
Run the tested code using eclipse-run as-Android Application
Load ddms on Eclipse, click File exploer, and browse all emulator-5554 files

Open/data/COM. calculator/files, Click Upload to device on the right side, and upload the CSV file to emulator.

4. Edit the test case. The code is/files/morebetter/Android code/androidcalculatortestapk.rar.

5. Run the test case
6. Write the test result to the file, which is stored under/data/COM. calculator/files.
7. Import the test results to the local computer.

3. Multiple activity tests

In the android SDK, there are two projects, "Notepad tutorial" and "activity testing", under "Resources"-"tutorials". An example shows how to quickly develop an android applet, one is to guide you how to test the project. Both projects are suitable for learning well at the beginning.
"Activity testing" tests the "samples"-"Spinner" project, including UI testing, State destruction, and State recovery testing. This project has only one activity, which is easy to test and can be completed by carefully reading the document. However, it should be difficult to see a program with only one activity. Should we test the multi-activity program?
In fact, I am just taking a look.

After viewing the test section of the SDK, you have the following questions:
Test activities, services, and providers are automated. How do we control the running process?
How to simulate operations on the interface, such as clicking a button and entering text content.

Create a project named login and the package named COM. vruc. android. login, the program name is login, and the activity name is authenticateactivity. Add a project named logintest and the package name is com. vruc. android. login. test: the project named logintest.
Complete login project:
1. Change the main. xml file name to login. XML, and change the code to the following:

<?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:orientation="vertical" android:layout_width="fill_parent"      android:layout_height="fill_parent">      <EditText android:id="@+id/username_field"          android:layout_height="wrap_content" android:layout_width="match_parent"></EditText>      <EditText android:id="@+id/password_field"          android:layout_height="wrap_content" android:layout_width="match_parent"></EditText>      <Button android:text="Login" android:id="@+id/login_button"          android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>  </LinearLayout>  

2. open authenticateactivity. in the Java file, add a click event for "@ + ID/login_button". The Code is to pass the input text in "@ + ID/username_field" to welcomeactivity and end the current activity, the Code is as follows:

public class AuthenticateActivity extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.login);Button login = (Button) findViewById(R.id.login_button);login.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Intent i = new Intent(AuthenticateActivity.this,WelcomeActivity.class);i.putExtra(ACCOUNT_SERVICE,((EditText) findViewById(R.id.username_field)).getText().toString());startActivity(i);finish();}});}}

3. Add the new file welcome. XML in the layout directory and change the code to the following:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><TextView android:id="@+id/welcome_message"android:layout_width="wrap_content" android:layout_height="wrap_content"android:textSize="15pt"></TextView></LinearLayout>

4. add a new welcomeactivity. java file and in androidmainifest. register in XML and override the oncreate event. The specific code is to assign a value to "@ + ID/welcome_message" and the value of "@ + ID/username_field" passed from loginactivity, the Code is as follows:

public class WelcomeActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.welcome);Intent i = this.getIntent();((TextView)findViewById(R.id.welcome_message)).setText(i.getStringExtra(ACCOUNT_SERVICE));}

Now you can run the login project and find that the text filled in "@ + ID/username_field" appears in welcomeactivity after you click "@ + ID/login_button.

Complete logintest Project
1. Add the logintest. Java file. The Inheritance class is Android. Test. instrumentationtestcase.
2. Complete Test code in logintest. Java:

Public static final string test_username = "test_username"; public static final string test_password = "test_password"; Public void testuserlogin () {// register the initial activity and run instrumentation = getinstrumentation (); activitymonitor monitor = instrumentation. addmonitor (authenticateactivity. class. getname (), null, false); // intent = new intent (intent. action_main); intent. setflags (intent. flag _ Activity_new_task); intent. setclassname (instrumentation. gettargetcontext (), authenticateactivity. class. getname (); instrumentation. startactivitysync (intent); // wait until the authenticate activity starts. Activity currentactivity = getinstrumentation (). waitformonitorwithtimeout (Monitor, 5); asserttrue (currentactivity! = NULL); // automatically enter the predefined user name view currentview = currentactivity. findviewbyid (COM. vruc. Android. login. R. Id. username_field); asserttrue (currentview! = NULL); touchutils. clickview (this, currentview); instrumentation. sendstringsync (test_username); // automatically enter the predefined password currentview = currentactivity. findviewbyid (COM. vruc. android. login. r. id. password_field); asserttrue (currentview! = NULL); touchutils. clickview (this, currentview); instrumentation. sendstringsync (test_password); // remove the current activity monitoring, register a new activity monitoring, and prepare instrumentation before pressing the button. removemonitor (MONITOR); monitor = instrumentation. addmonitor (welcomeactivity. class. getname (), null, false); // automatically click the login button currentview = currentactivity. findviewbyid (COM. vruc. android. login. r. id. login_button); asserttrue (currentview! = NULL); touchutils. clickview (this, currentview); // wait until the welcome activity starts currentactivity = getinstrumentation (). waitformonitorwithtimeout (Monitor, 5); currentview = currentactivity. findviewbyid (COM. vruc. android. login. r. id. welcome_message); asserttrue (currentview! = NULL); assertequals (test_username, (textview) currentview). gettext (). tostring ());}

After running the test program, you can find that testuserlogin passes smoothly, or you can view the specific running process in the simulator, just like you are new to the simulator.

4. The activity starts the Instrumentation Test.

Similar to startactivity and startservice
Start instrumentation in activity to call activityinstrumentationtestcase2
Try the following code
Startinstrumentation (New componentname ("com. example. Test", "android. Test. instrumentationtestrunner"), null, null );

5. Get data from intent

Most activities obtain some data from intent at startup.
When you use robotium for testing, you also need to obtain data from the activity.
The available process is
1. In the setup () method
Solo = new solo (getinstrumentation (), getactivity ());
Transfer to every testxxx method.
2. Before this statement, intent injection can be performed, for example

Intent intent=new Intent();  Bundle b=new Bundle();  b.putParcelable(Account.class.getName(), account);  b.putParcelable(User.class.getName(), user);  intent.putExtras(b);  setActivityIntent(intent);

3. Note that you need to put all the operations related to the activity in
Solo = new solo (getinstrumentation (), getactivity ();, for example
If the operation is stored in the local key-value, it must be performed after solo =. Otherwise, the activity will be instantiated in advance. Intent injection fails.

References:

Initial Exploration of android unit test-Instrumentation
Activity to start the Instrumentation Test
Learning noteslist (examples provided by robotium)
Android test-auto test multi activities
Robotium data-driven testing framework

Related Article

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.