简体   繁体   English

在以下情况下,我应该如何编写JUnit测试?

[英]How Should I write JUnit test in the following case?

I am new in the Unit Testing. 我是单元测试的新手。 I have a class Ckeckout which main function is to print the amount to be paid for books. 我有一个Ckeckout类,其主要功能是打印要支付的书籍费用。 The user types the titles of the books in the command line, and based on some calculations I have to output the final price. 用户在命令行中输入书籍的标题,根据一些计算,我必须输出最终价格。 Here is the Book class: 这是Book类:

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;
    }
}

And here is the Checkout class: 这是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
    }


}

What I want to test is just getPrice method. 我要测试的只是getPrice方法。 However, to do so, do I have to create list of Book objects in my CheckoutTest ? 但是,这样做是否必须在CheckoutTest创建Book对象列表? Also, I will have to verify the final result with some very long number (like 62.01997301). 另外,我将不得不用一些非常长的数字(例如62.01997301)来验证最终结果。 Isn't it easier, to test the main() method, since in my Unit test, there won't be any need to create the Book objects (I will work only with Strings ) and I can verify the output with shorter number (like 62.01)? 测试main()方法不是很容易,因为在我的单元测试中,不需要创建Book对象(我将仅使用Strings ),并且可以使用较短的数字来验证输出(像62.01)?

  1. However, to do so, do I have to create list of Book objects in my CheckoutTest?:Generally and in any kind - yeah ! 但是,要这样做,我是否必须在CheckoutTest中创建Book对象的列表?:通常和任何形式- 是的

  2. Also, I will have to verify the final result with some very long number (like 62.01997301): Naah , this depends on your targeting test/code quality! 另外,我还必须用一些很长的数字(例如62.01997301)来验证最终结果: 取决于您的定向测试/代码质量! (for a "price" 2 digits should be sufficient (in any country!?)) (对于“价格”,两位数字就足够了(在任何国家!!))

  3. Isn't it easier, to test the main() method, since in my Unit test, there won't be any need to create the Book objects (I will work only with Strings) and I can verify the output with shorter number (like 62.01)? 测试main()方法难道不是一件容易的事,因为在我的单元测试中,不需要创建Book对象(我将只使用Strings),并且我可以用较短的数字来验证输出(像62.01)? Definitely! 非也! But with the current setup some (human) would have to check the console for "passing that test", for JUnit(and programmatically testing the value), you should/will need to make "getPrice() more visible" ... or in some way access its value. 但是在当前设置下,某些(人工)将不得不检查控制台是否“通过了该测试”,对于JUnit(并以编程方式测试该值),您应该/将需要使“ getPrice()更加可见”……或以某种方式获取其价值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM