单元测试是在软件开发过程中,最低级别的测试活动,在该活动中软件的独立单元将在与程序的其他部分相隔离的情况下进行测试.android的单元测试其实也是一样的.
android中的测试框架是扩展的junit3,所以在学习android的单元测试之前,可以先学习junit3的使用.junit3要学习的东西其实也不多.
junit3的入门可以参考:http://android.blog.51cto.com/268543/49994
文档:http://wenku.baidu.com/view/87a176abd1f34693daef3e54.html
在android的单元测试中所涉及到的相关类:
ActivityInstrumentationTestCase:初次做测试的话可以暂时不用考虑该类.
ActivityInstrumentationTestCase2:该类主要进行activity的功能测试和activity的交互测试.例如:Activity的跳转,UI的交互等.我用的最多的就是这个类.
SingleLaunchActivityTestCase:该测试用例仅调用setUp()和tearDown()一次,与其他测试用例不一样的是每调用一次测试方法,就会重新调用setUp()和tearDown().所以该类是为了测试activity是否能够正确处理多次调用.
ActivityUnitTestCase:主要用于测试Activity,因为它允许注入MockContext和MockApplicaton,所以可以测试Activity在不同资源和应用的情况.
具体的还可以参考sdk文档:dev guide和api reference.
下图就是android中与测试相关类的uml图:
![](https://img-my.csdn.net/uploads/201205/28/1338175883_9108.png)
下面就拿一个具体的案例和大家讲解一下android中的单元测试是怎么实现的.首先需要说明的是这个案例是我在网上搜集来的,所以非常感谢博文:http://yuanzhifei89.iteye.com/blog/1122104
对该测试案例做一个简单的介绍:
包含三个Activity:MainActivity、HomeActivity、LoginActivity.
MainActivity:很简单就是一个Button,点击该Button进入到LoginActivity.
LoginActivity:四个可交互控件分别是:username、password、submit、reset
HomeActivity:显示LoginActivity提交过来的username、password
首先是demo这个android app的编写.
MainActivity的核心代码如下:
toLoginView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(intent);
}
});
LoginActivity的核心代码如下:
//declare widget
private EditText mUsernameView;
private EditText mPasswordView;
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
if(DEBUG) {
Log.i(TAG,"LoginActivity's onCreate");
}
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.act_login);
mUsernameView = (EditText)findViewById(R.id.username);
mPasswordView = (EditText)findViewById(R.id.password);
View submitView = findViewById(R.id.submit);
submitView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(DEBUG) {
Log.i(TAG,"submitView Clicked");
}
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
intent.putExtra(HomeActivity.EXTRA_USERNAME, mUsernameView.getText().toString());
intent.putExtra(HomeActivity.EXTRA_PASSWORD, mPasswordView.getText().toString());
startActivity(intent);
}
});
View resetView = findViewById(R.id.reset);
resetView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(DEBUG) {
Log.i(TAG,"resetView Clicked");
}
mUsernameView.setText("");
mPasswordView.setText("");
mUsernameView.requestFocus();
}
});
LoginActivity的布局文件的代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="@+id/label_username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="username:"
/>
<EditText
android:id="@+id/username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text"
/>
<TextView
android:id="@+id/label_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="password:"
/>
<EditText
android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
/>
<Button
android:id="@+id/submit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="submit"
/>
<Button
android:id="@+id/reset"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="reset"
/>
</LinearLayout>
HomeActivity的代码如下:
public class HomeActivity extends Activity {
private static final boolean DEBUG = true;
private static final String TAG = "--HomeActivity--";
public static final String EXTRA_USERNAME = "com.ceo.demo.activity.username";
public static final String EXTRA_PASSWORD = "com.ceo.demo.activity.password";
@Override
protected void onCreate(Bundle savedInstanceState) {
if(DEBUG) {
Log.i(TAG,"HomeActivity's onCreate");
}
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.act_home);
Intent intent = getIntent();
StringBuilder sb = new StringBuilder();
sb.append("username:").append(intent.getStringExtra(EXTRA_USERNAME)).append("\n");
sb.append("password:").append(intent.getStringExtra(EXTRA_PASSWORD));
TextView loginContentView = (TextView) findViewById(R.id.login_content);
loginContentView.setText(sb.toString());
}
}
至此,demo应用程序编写好了,下面就是demo_unittest的编写了.
第一步:新建demo_unittest项目,和新建一个android项目的步骤基本类似.
![](https://img-my.csdn.net/uploads/201205/28/1338176263_7468.jpg)
单击之后,弹出New Android Unit Test的对话框
Test Project Name:填写demo_unittest application name 也是这个
An existing Android Project:选择需要编写测试用例的项目----->这里我们选择demo
版本的选择,最好是和原项目的版本一致,避免不必要的错误.
这里需要注意一点就是包名的取名,最好是在原有项目的包名之后加上.test
点击finish之后,系统会自动为我们创建所需要的目录等信息.非常方便.
接下来可以选择AndroidManifest.xml文件,查看一下里面的构造,你会发现:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ceo.demo.activity.test"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-library android:name="android.test.runner" />
</application>
<uses-sdk android:minSdkVersion="8" />
<instrumentation android:targetPackage="com.ceo.demo.activity" android:name="android.test.InstrumentationTestRunner" />
</manifest>
系统自动帮我们添加了所需属性.
接下来就是测试类的编写:首先是MainActivityTest:
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {
//private static final String TAG = "=== MainActivityTest";
@SuppressWarnings("unused")
private Instrumentation mInstrument;
private MainActivity mActivity;
private View mToLoginView;
public MainActivityTest() {
super("com.ceo.demo.activity", MainActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
mInstrument = getInstrumentation();
// 启动被测试的Activity
mActivity = getActivity();
mToLoginView = mActivity.findViewById(com.ceo.demo.activity.R.id.to_login);
}
public void testPreConditions() {
// 在执行测试之前,确保程序的重要对象已被初始化
assertTrue(mToLoginView != null);
}
//@UiThreadTest 可以用在方法上,这样该方法就会在程序的ui线程上执行
@UiThreadTest
public void testToLogin() {
// @UiThreadTest注解使整个方法在UI线程上执行
mToLoginView.requestFocus();
mToLoginView.performClick();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
}
最主要的还是LoginActivityTest的编写,比较有代表性.
public class LoginActivityTest extends ActivityInstrumentationTestCase2<LoginActivity> {
private static final String TAG = "=== LoginActivityTest";
private Instrumentation mInstrument;
private LoginActivity mActivity;
private EditText mUsernameView;
private EditText mPasswordView;
private View mSubmitView;
private View mResetView;
public LoginActivityTest() {
super("com.ceo.demo.activity", LoginActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
/*
* 要向程序发送key事件的话,必须在getActivity之前调用该方法来关闭touch模式
* 否则key事件会被忽略
*/
setActivityInitialTouchMode(false);
mInstrument = getInstrumentation();
mActivity = getActivity();
Log.i(TAG, "current activity: " + mActivity.getClass().getName());
mUsernameView = (EditText) mActivity.findViewById(com.ceo.demo.activity.R.id.username);
mPasswordView = (EditText) mActivity.findViewById(com.ceo.demo.activity.R.id.password);
mSubmitView = mActivity.findViewById(com.ceo.demo.activity.R.id.submit);
mResetView = mActivity.findViewById(com.ceo.demo.activity.R.id.reset);
}
public void testPreConditions() {
assertTrue(mUsernameView != null);
assertTrue(mPasswordView != null);
assertTrue(mSubmitView != null);
assertTrue(mResetView != null);
}
public void testInput() {
input();
assertEquals("yuan", mUsernameView.getText().toString());
assertEquals("1123", mPasswordView.getText().toString());
}
public void testSubmit() {
input();
mInstrument.runOnMainSync(new Runnable() {
public void run() {
mSubmitView.requestFocus();
mSubmitView.performClick();
}
});
}
public void testReset() {
input();
mInstrument.runOnMainSync(new Runnable() {
public void run() {
mResetView.requestFocus();
mResetView.performClick();
}
});
assertEquals("", mUsernameView.getText().toString());
assertEquals("", mPasswordView.getText().toString());
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
private void input() {
mActivity.runOnUiThread(new Runnable() {
public void run() {
mUsernameView.requestFocus();
}
});
// 因为测试用例运行在单独的线程上,这里最好要
// 同步application,等待其执行完后再运行
mInstrument.waitForIdleSync();
sendKeys(KeyEvent.KEYCODE_Y, KeyEvent.KEYCODE_U,
KeyEvent.KEYCODE_A, KeyEvent.KEYCODE_N);
// 效果同上面sendKeys之前的代码
mInstrument.runOnMainSync(new Runnable() {
public void run() {
mPasswordView.requestFocus();
}
});
sendKeys(KeyEvent.KEYCODE_1, KeyEvent.KEYCODE_1,
KeyEvent.KEYCODE_2, KeyEvent.KEYCODE_3);
}
}
HomeActivity的编写:
public class HomeActivityTest extends ActivityUnitTestCase<HomeActivity> {
//private static final String TAG = "=== HomeActivityTest";
private static final String LOGIN_CONTENT = "username:yuan\npassword:1123";
private HomeActivity mHomeActivity;
private TextView mLoginContentView;
public HomeActivityTest() {
super(HomeActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
Intent intent = new Intent();
intent.putExtra(HomeActivity.EXTRA_USERNAME, "yuan");
intent.putExtra(HomeActivity.EXTRA_PASSWORD, "1123");
mHomeActivity = launchActivityWithIntent("com.ceo.demo.activity", HomeActivity.class, intent);
mLoginContentView = (TextView) mHomeActivity.findViewById(com.ceo.demo.activity.R.id.login_content);
}
public void testLoginContent() {
assertEquals(LOGIN_CONTENT, mLoginContentView.getText().toString());
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
}
最后就是检验成果的时候了:
右击项目的包名,run as Android Junit Test
![](https://img-my.csdn.net/uploads/201205/28/1338176428_8802.jpg)
注意事项:
#1.如果没有预先安装项目的话,在做单元测试的时候会先安装项目到您的模拟器或者真机上,然后再执行单元测试.
#2.对Activity的测试,不一定非要从程序的Launch Activity开始,一步一步往下执行,可以从任意一个需要测试的Activity开始执行.
#3.在测试类中怎样获取控件:toLoginView是一个Button,View toLoginView = findViewById(R.id.to_login);
#4.从一个Activity启动另一个Activity,Intent intent = new Intent(getApplicationContext(),LoginActivity.class);
#5.获得当前的Activity再调用Activity的add方法--->最后进行预期值和实际值的判断,assertEquals(5, getActivity().add(2, 3));
#6.直接在UI线程中执行模拟事件,容易造成UI线程堵塞,解决方案在后面的博文中给出.
#7.protected void setUp()----->Sets up the fixture, for example, open a network connection. This method is called before a test is executed.
#8.protected void tearDown()----->Make sure all resources are cleaned up and garbage collected before moving on to the next test. Subclasses that override this method should make sure they call super.tearDown() at the end of the overriding method.
#9.setUp()用来初始设置。例如:启动Activity、初始化资源等,tearDown()用来垃圾的清理以及资源的回收等。例如:关闭数据库、finish Activity等
扩展阅读:
开发自动化:http://www.ibm.com/developerworks/cn/java/j-ap01117/index.html
代码覆盖率:http://www.cnblogs.com/coderzh/archive/2009/03/29/1424344.html
单元测试汇总:http://www.51testing.com/html/94/category-catid-94.html
集成测试和单元测试的关系:http://www.outsourcing.org.cn/newsshow.asp?newsid=162&classid=17
单元测试和单元测试框架:http://www.51testing.com/zhuanti/unit/unit.html