我是單元測試新手。 我有一個類Ckeckout
,其主要功能是打印支付書籍的金額。用戶在命令行輸入圖書的標題,根據一些計算,我必須輸出最終價格。 這裏是Book
類:如何在以下情況下編寫JUnit測試?
public class Book {
private String title;
private double price;
private int year;
public Book(String title, double price, int year) {
super();
this.title = title;
this.price = price;
this.year = year;
}
}
這裏是Checkout
類:
public class Checkout {
private List<Book> books;
public Checkout(List<Book> books) {
super();
this.books = books;
}
//calculate the final price
private double getPrice(){
//return some double
}
}
我想測試只是getPrice
方法。但是,要這樣做,是否必須在我的CheckoutTest
中創建Book
對象列表?另外,我將不得不用最長的數字來驗證最終結果(如62.01997301)。測試main()方法並不容易,因爲在我的單元測試中,不需要創建Book
對象(我只能使用Strings
),並且我可以使用較短的數字驗證輸出(像62.01)?
只是想評論,你可能不應該使用雙重存儲價格,因爲浮點類型固有的不準確性。 – juunas 2015-04-06 10:10:21