一种是项目内测试,另一种是新建一个Junit工程。
第一种情况时,
要在本项目AndroidManifest.xml中作出配置:
<!-- 在本应用中导入需要使用的包,放在application里面activity外面 -->
<uses-library android:name="android.test.runner"/>
<!-- 记住这个一要放在application外面,不然会出现配置错误 信息 -->
意思是,注册测试机。com.example.demo_junit为要测试的包。
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.example.demo_junit">
</instrumentation>
下面写一个具体的例子:
首先配置AndroidManifest.xml,具体如上
接着新建Service类:
1 public class Service { 2 public int add(int a,int b){ 3 return a+b; 4 } 5 } |
然后在建立Junit类时,一定要继承AndroidTestCase:
1 public class Junit extends AndroidTestCase { 2 public void test(){ 3 Service service=new Service(); 4 System.out.println(service.add(2, 5)); 5 } 6 } |
好了,现在可以测试了。
将鼠标光标移至Junit类的test()方法上,单击右键,选择Run As/Android JUnit Test即可。
如果出现绿色条纹则表示测试的代码是正确的,红色为错误的: