1.首先需要在AndroidManifest下添加相关内容
<application android:icon="@drawable/icon" android:label="@string/app_name"> <!-- 单元测试使用android.test.runner --> <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 --> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.hoo.file" android:label="Tests for My App" />
2.编写测试方法
public class PersonService { public int save() { String in = "78"; int b = new Integer(in); return b; } }
public class PersonServiceTest extends AndroidTestCase { private static final String TAG = "PersonServiceTest"; public void testSave() throws Throwable { PersonService service = new PersonService(); int b = service.save();//检验save()方法运行是否正常 Log.i(TAG, "result="+ b); System.out.println("hukaihukai"); System.err.println("result="+ b); Assert.assertEquals(78, b); } }
3.右键项目Run as ->Android Junit Test,在Junit窗口中可以查看是否出错,绿色代表正常