Java对类进行单元测试
class Employee { public Employee(String n, double s, int year, int month, int day){ name = n; salary = s; LocalDAte hireDay = LocalDate.now(year, month, day); } ・・・・・・(省略) public static void main(String[] args) { Employee e = new Employee("Herry", 5000, 2003, 3, 21); System.out.println(e.getName() + " " + e.getSalary()); } }
如果想要独立地测试Employee类,只需要执行
java Employee
如果Employee类只是一个更大型的应用程序的一部分,就可以使用下面这条语句运行程序
java Application
java Application
Employee类的main方法永远不会执行。
完整程序:
package Employee; import java.time.LocalDate; /** * 《 Java核心技术 卷I 》P104:程序清单4-2 * EmployeeTest/EmployeeTest.java * @author Gordo_li * */ public class EmployeeTest { public static void main(String[] args) { // TODO Auto-generated method stub Employee[] staff = new Employee[3]; staff[0] = new Employee("Carl", 75000, 1987, 12, 15); staff[1] = new Employee("Harry", 50000, 1989, 10, 1); staff[2] = new Employee("Tony", 40000, 1990, 3,15); for (Employee e: staff) e.raiseSalary(5); for (Employee e: staff) System.out.println("name = " + e.getName() + ", salary = " + e.getSalary() + ", hireDay = " + e.getHireDay()); } } class Employee { private String name; private double salary; private LocalDate hireDay; public Employee(String n, double s, int year, int month, int day){ name = n; salary = s; LocalDate hrieDay = LocalDate.of(year, month, day); } public String getName(){ return name; } public double getSalary(){ return salary; } public LocalDate getHireDay() { return hireDay; } public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } }
文章来源: https://blog.csdn.net/Gordo_Li/article/details/96485594