notyy的junit教程
作者:網絡轉載 發(fā)布時間:[ 2013/1/7 15:37:57 ] 推薦標簽:
先寫test
public void testDiscount(){
AccountA=new Account("notyy",100);
AccountB=new Account("bricks",200);
AccountA.discount(50);
//100-50=50
assertEquals(50.00,AccountA.getBalance(),2);
AccountB.discount(120);
//200-120=80
assertEquals(80,AccountB.getBalance(),2);
}
然后實現
public void discount(double aMoney){
Balance-=aMoney;
}
后是轉帳功能,轉帳是從一個帳戶轉到另一個帳戶。其實是調用一個帳戶的增加功能和另一個帳戶的減少功能。
每個測試里都要建立accountA和accountB是不是很煩,junit考慮到了這一點,所以可以覆蓋testcase的setUp方法,在該方法內建立一些所有test都要用到的變量等。
public void setUp(){
AccountA=new Account("notyy",100);
AccountB=new Account("bricks",200);
}
這樣,所有的測試方法中都不用再建立這兩個實例了。:)
好,寫轉帳方法的測試
public void testTransfer(){
AccountA.transfer(AccountB,80.00);
//100-80=20
//200+80=280
assertEquals(20.00,AccountA.getBalance(),2);
assertEquals(280.00,AccountB.getBalance(),2);
}
然后建立transfer方法的框架,使它能編譯:
public void transfer(Account aAccount,double aBalance){}
測試時報失敗,expected “20” but was “100”
然后填入實現 :
public void transfer(Account aAccount,double aBalance){
this.discount(aBalance);
aAccount.credit(aBalance);
}
test OK!
簡單的步驟,卻可使你對你實現的方法的正確性確信無疑,而且寫測試的過程也是設計的過程,如果在寫一個方法前,你連應該得到的輸出都想不明白,又怎么能動手去寫呢?
誰說XP只要code,不要設計呢? :)
好了,junit單元測試的第一個例子寫到這吧。很簡單吧?