以下以銀行余額、存款、取款為例
一、Junit配置
Junit同Eclipse一同提供,無需下載。要使用Junit必須先將Junit jar 保存在項目的build路徑上,並創建一個測試類,步驟如下:
1)法一:

法二:點擊項目test001,右鍵-propreties
2)選擇Libraries,點擊Add variable按鈕,輸入變量名JUNIT_LIB,路徑:E:\測試\測試工具\Juint\eclipse\eclipse-jee-kepler-SR2-win32\eclipse\plugins\org.junit_4.11.0.v201303080030,結果如下圖:

二、編寫測試類和代碼、執行測試用例
1)新建測試類:New-Junit Test Case

2)編寫測試代碼:
1 package testsample; 2 3 import org.junit.After; 4 import org.junit.Before; 5 import junit.framework.TestCase; 6 public class Tc_Account extends TestCase { 7 8 public Tc_Account(String arg0) 9 { 10 super(arg0); 11 } 12 @Before 13 public void setUp() throws Exception { 14 super.setUp() ; 15 } 16 public void testDeposit(){ 17 Account account=new Account(); 18 assertEquals("Account should start with no funds.",1,account.balance()); 19 20 account.deposit(5); 21 assertEquals("Account should reflect deposit.", 7, account.balance()); 22 } 23 24 public void testwithdraw(){ 25 Account account=new Account(); 26 account.deposit(5); 27 account.withdraw(3); 28 assertEquals("Account should reflect withdarw.", 3, account.balance()); 29 } 30 31 @After 32 public void tearDown() throws Exception { 33 super.tearDown(); 34 } 35 }
3)新建Acoount類,實現銀行的余額、存款、取款:
1 package testsample; 2 3 public class Account { 4 protected int balance; 5 public int balance(){ 6 return balance; 7 } 8 public void deposit(int amount){ 9 balance+=amount; 10 } 11 public void withdraw(int amount){ 12 balance-=amount; 13 } 14 }
4)執行測試用例:右鍵項目testsample-Run as-Junit Test Case,通過failure trace可以查看錯誤信息

5)調整測試用例中的預期值:
1 package testsample; 2 3 import org.junit.After; 4 import org.junit.Before; 5 import junit.framework.TestCase; 6 public class Tc_Account extends TestCase { 7 8 public Tc_Account(String arg0) 9 { 10 super(arg0); 11 } 12 @Before 13 public void setUp() throws Exception { 14 super.setUp() ; 15 } 16 public void testDeposit(){ 17 Account account=new Account(); 18 assertEquals("Account should start with no funds.",0,account.balance()); 19 20 account.deposit(5); 21 assertEquals("Account should reflect deposit.", 5, account.balance()); 22 } 23 24 public void testwithdraw(){ 25 Account account=new Account(); 26 account.deposit(5); 27 account.withdraw(3); 28 assertEquals("Account should reflect withdarw.", 2, account.balance()); 29 } 30 31 @After 32 public void tearDown() throws Exception { 33 super.tearDown(); 34 } 35 }
6)執行測試用例,結果如下:所有測試通過

