单元测试

一、视频笔记

1. 单元测试:检查程序执行过程执行结果是否正确。

2.配置:

(1)引入单元测试的环境

<application>中——单元测试需要的依赖库引入到项目中

(2)配置单元测试的启动装置

<manifest>中——

如下:

AndroidManifest.xml:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.example.junitest"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-sdk
 8         android:minSdkVersion="14"
 9         android:targetSdkVersion="21" />
10 
11     <application
12         android:allowBackup="true"
13         android:icon="@drawable/ic_launcher"
14         android:label="@string/app_name"
15         android:theme="@style/AppTheme" >
16        
17         <activity
18             android:name=".MainActivity"
19             android:label="@string/app_name" >
20             <intent-filter>
21                 <action android:name="android.intent.action.MAIN" />
22 
23                 <category android:name="android.intent.category.LAUNCHER" />
24             </intent-filter>
25         </activity>
26         
27          <uses-library android:name="android.test.runner"/>
28     </application>
29     
30     <instrumentation 
31         android:name="android.test.InstrumentationTestRunner"
32         android:targetPackage="com.example.junitest"
33         android:label="Test for My App"
34         ></instrumentation>
35 
36 </manifest>

二、实践

1.建立单元测试类:

 1 package com.example.service;
 2 
 3 public class PersonService {
 4 
 5     public void save(String username)
 6     {
 7         String sub = username.substring(6);//从6开始取一段字符,如果输入参数为空,会出错
 8     }
 9     
10     public int add(int a ,int b)//判断这个方法的处理结果是否正确
11     {
12         return a+b;
13     }
14 }

2.编写单元测试代码:

 1 package com.example.junit;
 2 
 3 import junit.framework.Assert;
 4 
 5 import com.example.service.PersonService;
 6 
 7 import android.test.AndroidTestCase;
 8 
 9 public class PersonServiceTest extends AndroidTestCase {
10 
11     
12     public void testSave()throws Exception 
13     {
14         PersonService service = new PersonService();
15         service.save(null);
16     }
17     
18     public void testAdd()throws Exception 
19     {
20         PersonService service = new PersonService();
21         int actual = service.add(1, 2);
22         Assert.assertEquals(3, actual);
23     }
24 }

3.选择要测试的方法,右键点击“Run As”-"Android Junit Test":

本例中:Outline—com.example.junit—PersonServiceTest—testSave()和testAdd()分别选中,右键点击“Run As”-"Android Junit Test"。

备注:连接真机测试时,如果一个手机测试不通过,建议换个手机再试一次。

原文地址:https://www.cnblogs.com/ttzm/p/7225102.html