这里使用的环境是:Eclipse / Android / JUnit3,没办法,我试过了,Android目前貌似应该还无法支持JUnit4,所有的Test Case都必须继承于AndroidTestCase。好吧,反正JUnit 3也还比较容易理解。
新建一个Demo工程,注意同时建立一个AndroidTest Project(当然这个Test Project你也可以稍后建立)。
工程中添加我们的测试对象,并完成相应用来测试的方法:
package com.freesoft.demo.utils; /** * 被测试数学工具类 * @author Sandy * */ public class MathUtil { /** * 加法方法 * @param num1, 操作数1 * @param num2, 操作数2 * @return 返回两数相加值 */ public int add(int num1, int num2) { return num1 + num2; } /** * 减法方法 * @param num1, 操作数1 * @param num2, 操作数2 * @return 返回两数相减值 */ public int sub(int num1, int num2) { return num1 - num2; } /** * 乘法方法 * @param num1, 操作数1 * @param num2, 操作数2 * @return 返回两数相乘值 */ public int mul(int num1, int num2) { return num1 * num2; } /** * 除法方法 * @param num1, 操作数1 * @param num2, 操作数2 * @return 返回两数相除值 * @throws Exception 抛出的异常 */ public int div(int num1, int num2) throws ArithmeticException { int result = 0; try { result = num1 / num2; } catch (ArithmeticException e) { throw e; }; return result; } /** * 取余方法 * @param num1, 操作数1 * @param num2, 操作数2 * @return 返回两数取余值 */ public int mod(int num1, int num2) { return num1 % num2; } }
之后请检查Test Project中manifest.xml文件的Application小节中是否存在如下字段:
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <uses-library android:name="android.test.runner" /> </application>
此时测试工具类如下:
/** * */ package com.freesoft.demo.utils; import android.test.AndroidTestCase; /** * @author Sandy * */ public class MathUtilTest extends AndroidTestCase { /* (non-Javadoc) * @see android.test.AndroidTestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); } /* (non-Javadoc) * @see android.test.AndroidTestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); } /** * Test method for {@link com.freesoft.demo.utils.MathUtil#add(int, int)}. */ public void testAdd() { fail("Not yet implemented"); } /** * Test method for {@link com.freesoft.demo.utils.MathUtil#sub(int, int)}. */ public void testSub() { fail("Not yet implemented"); } /** * Test method for {@link com.freesoft.demo.utils.MathUtil#mul(int, int)}. */ public void testMul() { fail("Not yet implemented"); } /** * Test method for {@link com.freesoft.demo.utils.MathUtil#div(int, int)}. */ public void testDiv() { fail("Not yet implemented"); } /** * Test method for {@link com.freesoft.demo.utils.MathUtil#mod(int, int)}. */ public void testMod() { fail("Not yet implemented"); } }
右键工具类,选择Run as Android JUnit Test,运行正常,可以看到
至此,一个简单的Unit Test搞定。