JUnit 是一个可用于执行软件单元测试的程序,它使用一组用 Java 编写的测试用例实现这种测试。JUnit 的一般用法是创建一组单元测试,对软件进行更改时,这组单元测试可以自动运行。这样,开发人员可以确保对他们正在创建的软件所做的改动不会破坏软件以前实 现的功能。JUnit 甚至还提供了一种被称作测试驱动开发 (TDD) 的开发方法,该方法主张甚至在编写某个软件之前先编写测试它的单元测试。JUnit 还提供了一个测试运行器,能够运行单元测试并报告测试是否成功。

阅读有关 JUnit 的资料时可能遇到的一些常用术语包括:

  • 测试方法: Java 类中的一个方法,它包含一个单元测试。
  • 测试类: 包含一个或多个测试方法的 Java 类。
  • 断言: 您在测试方法中包括的一条语句,用于检查测试结果是否如预期的那样。
  • 测试固件 (Test Fixture): 用于设置多个测试的状态的类;通常在设置例程“代价高昂”或执行时间过长时使用。
  • 测试套件: 一起运行的一组测试类。

 1  <? xml version="1.0" encoding="utf-8" ?>
 2  < manifest  xmlns:android ="http://schemas.android.com/apk/res/android"
 3      package ="com.gaolei.juint"
 4      android:versionCode ="1"
 5      android:versionName ="1.0"   >
 6 
 7       < uses-sdk  android:minSdkVersion ="15"   />
 8 
 9       < application
10           android:icon ="@drawable/ic_launcher"
11          android:label ="@string/app_name"   >
12           < activity
13               android:name =".JunitestActivity"
14              android:label ="@string/app_name"   >
15               < intent-filter >
16                   < action  android:name ="android.intent.action.MAIN"   />
17 
18                   < category  android:name ="android.intent.category.LAUNCHER"   />
19               </ intent-filter >
20           </ activity >
21          
22           < uses-library  android:name ="android.test.runner" />
23       </ application >
24       < instrumentation  android:name ="android.test.InstrumentationTestRunner"
25          android:targetPackage ="com.gaolei.juint"  android:label ="Tests for My Apps" >        
26       </ instrumentation >
27 
28  </ manifest >

 1  package  com.gaolei.test;
 2 
 3  import  junit.framework.Assert;
 4 
 5  import  com.gaolei.service.PersonService;
 6 
 7  import  android.test.AndroidTestCase;
 8 
 9  public   class  PersonServiceTest  extends  AndroidTestCase {
10 
11       public   void  testSave()  throws  Exception {
12          PersonService personService  =   new  PersonService();
13          personService.save( null );
14      }
15 
16       public   void  testAdd()  throws  Exception {
17          PersonService personService  =   new  PersonService();
18           int  actual  =  personService.add( 1 2 );
19          Assert.assertEquals( 3 , actual);
20      }
21  }
22 

 1  package  com.gaolei.test;
 2 
 3  import  junit.framework.Assert;
 4 
 5  import  com.gaolei.service.PersonService;
 6 
 7  import  android.test.AndroidTestCase;
 8 
 9  public   class  PersonServiceTest  extends  AndroidTestCase {
10 
11       public   void  testSave()  throws  Exception {
12          PersonService personService  =   new  PersonService();
13          personService.save( null );
14      }
15 
16       public   void  testAdd()  throws  Exception {
17          PersonService personService  =   new  PersonService();
18           int  actual  =  personService.add( 1 2 );
19          Assert.assertEquals( 3 , actual);
20      }
21  }
22 
对应用进行单元测试_第1张图片