JUnit 是一個可用于執(zhí)行軟件單元測試的程序,它使用一組用 Java 編寫的測試用例實(shí)現(xiàn)這種測試。JUnit 的一般用法是創(chuàng)建一組單元測試,對軟件進(jìn)行更改時,這組單元測試可以自動運(yùn)行。這樣,開發(fā)人員可以確保對他們正在創(chuàng)建的軟件所做的改動不會破壞軟件以前實(shí) 現(xiàn)的功能。JUnit 甚至還提供了一種被稱作測試驅(qū)動開發(fā) (TDD) 的開發(fā)方法,該方法主張甚至在編寫某個軟件之前先編寫測試它的單元測試。JUnit 還提供了一個測試運(yùn)行器,能夠運(yùn)行單元測試并報告測試是否成功。
閱讀有關(guān) JUnit 的資料時可能遇到的一些常用術(shù)語包括:
- 測試方法: Java 類中的一個方法,它包含一個單元測試。
- 測試類: 包含一個或多個測試方法的 Java 類。
- 斷言: 您在測試方法中包括的一條語句,用于檢查測試結(jié)果是否如預(yù)期的那樣。
- 測試固件 (Test Fixture): 用于設(shè)置多個測試的狀態(tài)的類;通常在設(shè)置例程“代價高昂”或執(zhí)行時間過長時使用。
- 測試套件: 一起運(yùn)行的一組測試類。
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