歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 對Android應用進行單元測試

對Android應用進行單元測試

日期:2017/3/1 9:56:41   编辑:Linux編程

是關於對Android應用進行單元測試的,在android應用開發中很常用的,可以測試android應用的代碼測試、檢測程序處理的正確性,在一個應用開發中單元測試框架是不可必少的,下面通過一個例子來進行講解:

我的思路:

首先創建個單元測試項目,再在項目中創建一個被測試的類文件,通過單元測試對被測試類裡面的一個方法進行測試,為了好解釋就寫給簡單的了,

代碼如下:

package com.betest.test;

public class betest {

public int test() {
String in = "test";
int b = new Integer(in);

}
}

從上面看代碼執行的過程中會出錯吧

下面編輯測試文件:

因為是在android項目中使用單元測試,首先需要在項目功能清單文件(也就是AndroidMainfest.xml)中加入調用測試類庫。

代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.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" />
<activity android:name=".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>

</application>
<uses-sdk android:minSdkVersion="8" />
<!-- 包名要去測試文檔包名相同 -->
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.test.test" />
</manifest>

上面的代碼中也就是加入了

<uses-library android:name="android.test.runner" />

<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.test.test" />

這兩句話。

開始創建測試類,創建個單元測試方法,代碼如下:

package com.test.test;

import junit.framework.Assert;
import com.betest.test;
import android.test.AndroidTestCase;
import android.util.Log;

public class PersonServiceTest extends AndroidTestCase {


public void testtest() throws Throwable{
PersonService service = new PersonService();
service.test();//檢驗save()方法運行是否正常

}
}

到這裡代碼已經寫完,下面就開始進行測試了,在outline裡面找到相應的單元測試方法,右鍵 找到 Android Junit Test 在日志文件中就可以看到錯誤原因了。

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved