CalcService.java
package com.demo.junittest.service;
public class CalcService {
private static final String tag = "CalcService";
public int add(int x,int y){
int result = x + y;
return result;
}
public int sub(int x,int y){
return x - y;
}
}
Test.java
package com.demo.junittest.test;
import com.demo.junittest.service.CalcService;
import android.test.AndroidTestCase;
public class Test extends AndroidTestCase {
private CalcService service;
/**
* 测试框架,被初始化的时候执行该方法
*/
@Override
protected void setUp() throws Exception {
service = new CalcService();
super.setUp();
}
/**
* 测试框架,执行完毕后调用的方法
*/
@Override
protected void tearDown() throws Exception {
service = null;
super.tearDown();
}
/**
* 测试相加
* 向测试框架抛出异常
* 程序实际上是运行在android手机里面的虚拟机里面
*/
public void testAdd() throws Exception{
int result = service.sub(10, 3);
assertEquals(7, result); //断言,断言边界,特殊情况
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demo.junittest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:label="Tests for My App"
android:targetPackage="com.demo.junittest" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<uses-library android:name="android.test.runner" />
<activity
android:name="com.demo.junittest.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>
</manifest>
笔记:
对应用进行单元测试
在实际开发中,开发android软件的过程需要不断地进行测试。而使用Junit测试框架,侧是正规Android开发的必用技术,在Junit中可以得到组件,可以模拟发送事件和检测程序处理的正确性。
第一步:首先在AndroidManifest.xml中加入下面红色代码:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.itcast.action“ 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="6" />
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="cn.itcast.action" android:label="Tests for My App" />
</manifest>
上面targetPackage指定的包要和应用的package相同。
第二步:编写单元测试代码(选择要测试的方法,右键点击“Run As”--“Android Junit Test” ):
import android.test.AndroidTestCase;
import android.util.Log;
public class XMLTest extends AndroidTestCase {
public void testSomething() throws Throwable {
Assert.assertTrue(1 + 1 == 3);
}
}