Android unit test instrumentation

Source: Internet
Author: User

During development, we need to perform unit tests on some functions and start activity to test some small functions. This is a bit of a fuss.

We can use the android unit test tool

This article is just an introduction to the effect of brick throwing.

Instrumentation has no interface and can be started.

The following is a simple example to explain the basic test method of instrumentation:


Our test project

Androidmanifest. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: Android = "http://schemas.android.com/apk/res/android" package = "CN. HPC. assistant "Android: versioncode =" 1 "Android: versionname =" 1.0 "> <uses-SDK Android: minsdkversion =" 8 "Android: targetsdkversion = "14"/> <application Android: Name = ". floatapplication "Android: allowbackup =" true "Android: icon =" @ drawable/ic_launcher "Android: Label =" @ string/app_name "Android: theme = "@ style/apptheme" Android: d Ebuggable = "true"> <activity Android: Name = "CN. HPC. assistant. mainactivity "Android: Label =" @ string/app_name "> <intent-filter> <action Android: Name =" android. intent. action. main "/> <category Android: Name =" android. intent. category. launcher "/> </intent-filter> </activity> <uses-library Android: Name =" android. test. runner "/> <! -- Eight shares: Introduce the test database --> </Application> <! -- Eight-part article: name of the tested target package and instrumentation. --> <Instrumentation Android: Name = "android. test. instrumentationtestrunner "Android: Label =" tests for my app "Android: targetpackage =" CN. HPC. assistant "/> </manifest>

Mainactivity. Java

package cn.hpc.assistant;import android.app.Activity;import android.content.Context;import android.graphics.PixelFormat;import android.graphics.Point;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.Gravity;import android.view.View;import android.view.WindowManager;import android.view.WindowManager.LayoutParams;import android.widget.TextView;public class MainActivity extends Activity {private TextView tv = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv = (TextView) this.findViewById(R.id.text1);this.findViewById(R.id.id_btn_fun).setOnClickListener(mOnClickListener);}View.OnClickListener mOnClickListener = new View.OnClickListener() {@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.id_btn_fun:fun();break;default:}}};private void fun(){tv.setText(android.os.Build.MODEL + android.os.Build.getRadioVersion());}}

Layout file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:orientation="horizontal"    tools:context=".MainActivity" >    <TextView        android:id="@+id/text1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true"        android:text="@string/hello_world" />    <Button        android:id="@+id/id_btn_fun"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <Button        android:id="@+id/id_btn_day"        android:layout_width="wrap_content"        android:layout_height="wrap_content"         android:text="Day"/>    <Button        android:id="@+id/id_btn_night"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Night" /></LinearLayout>

Key test file:

Package CN. HPC. assistant. test; import JUnit. framework. assert; import android. content. intent; import android. OS. systemclock; import android. test. instrumentationtestcase; import android. widget. button; import android. widget. textview; import CN. HPC. assistant. mainactivity; import CN. HPC. assistant. r; public class testmyapp extends instrumentationtestcase {mainactivity mactivity = NULL; private button = NULL; private textview text = NULL; Public void testsample () throws throwable {assert. asserttrue (1 + 1 = 3); // test an error result} @ overrideprotected void teardown () throws exception {// todo auto-generated method stubmactivity. finish (); super. teardown () ;}@ overrideprotected void setup () throws exception {// todo auto-generated method stubsuper. setup (); intent = new intent (); intent. setclassname ("CN. HPC. assistant ", mainactivity. class. getname (); intent. setflags (intent. flag_activity_new_task); mactivity = (mainactivity) getinstrumentation (). startactivitysync (intent); text = (textview) mactivity. findviewbyid (R. id. text1); button = (button) mactivity. findviewbyid (R. id. id_btn_fun);}/*** activity function test */Public void testactivity () throws exception {// test the robustness of the key. A function is run 100 times in a row, click button 100 times for (INT I = 0; I <100; ++ I) {getinstrumentation (). runonmainsync (New javasmclick (button); systemclock. sleep (500); // The interval between 0.5 seconds} assertequals ("android instrumentationtestcase", text. gettext (). tostring (); // check the output result after running}/*** interface for clicking the simulated button */private class implements mclick implements runnable {button BTN; Public implements mclick (Button button) {BTN = button;} public void run () {BTN. optional mclick ();}}}

Android developer has the following explanation:

Protected void setup ()

Since: API level 3

Sets up the fixture, for example, open a network connection. This method is called before a test is executed.

Setup () is used for initial settings, such as starting an activity and initializing resources.

Protected void teardown ()

Since: API level 3

Make sure all resources are cleaned up and garbage collected before moving on to the next test. subclasses that override this method shocould make sure they call super. teardown () at the end of the overriding method.

Teardown () is used for garbage cleaning and Resource Recycling.



In this test method, a button click event is simulated to check whether the program runs as expected.

Here, the invoke mclick method introduces the runnable interface to execute simulated events through threads. This benefit does not block the UI thread.

Start the test with the JUnit tool integrated with eclipse

In eclipse, right-click the project sample and choose Android JUnit test from the run as sub-menu options.


After the test, the error message in the test is displayed,

Finished,

You are welcome to reprint it. Please indicate the source for reprinting. Thank you!

Http://blog.csdn.net/hpccn/article/details/8439784

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.