JUnit – 编写测试 云少 2019-12-06 2019-12-06 六、JUnit – 编写测试 在这里你将会看到一个应用 POJO 类,Business logic 类和在 test runner 中运行的 test 类的 JUnit 测试的例子。
在 C:\ > JUNIT_WORKSPACE 路径下创建一个名为 EmployeeDetails.java 的 POJO 类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 public class EmployeeDetails { private String name; private double monthlySalary; private int age; public String getName () { return name; } public void setName (String name) { this .name = name; } public double getMonthlySalary () { return monthlySalary; } public void setMonthlySalary (double monthlySalary) { this .monthlySalary = monthlySalary; } public int getAge () { return age; } public void setAge (int age) { this .age = age; } }
EmployeeDetails 类被用于
取得或者设置雇员的姓名的值 取得或者设置雇员的每月薪水的值 取得或者设置雇员的年龄的值 在 C:\ > JUNIT_WORKSPACE 路径下创建一个名为 EmpBusinessLogic.java 的 business logic 类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class EmpBusinessLogic { public double calculateYearlySalary (EmployeeDetails employeeDetails) { double yearlySalary=0 ; yearlySalary = employeeDetails.getMonthlySalary() * 12 ; return yearlySalary; } public double calculateAppraisal (EmployeeDetails employeeDetails) { double appraisal=0 ; if (employeeDetails.getMonthlySalary() < 10000 ){ appraisal = 500 ; }else { appraisal = 1000 ; } return appraisal; } }
EmpBusinessLogic 类被用来计算
在 C:\ > JUNIT_WORKSPACE 路径下创建一个名为 TestEmployeeDetails.java 的准备被测试的测试案例类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 import org.junit.Test;import static org.junit.Assert.assertEquals;public class TestEmployeeDetails { EmpBusinessLogic empBusinessLogic = new EmpBusinessLogic (); EmployeeDetails employee = new EmployeeDetails (); @Test public void testCalculateAppriasal () { employee.setName("Rajeev" ); employee.setAge(25 ); employee.setMonthlySalary(8000 ); double appraisal= empBusinessLogic.calculateAppraisal(employee); assertEquals(500 , appraisal, 0.0 ); } @Test public void testCalculateYearlySalary () { employee.setName("Rajeev" ); employee.setAge(25 ); employee.setMonthlySalary(8000 ); double salary= empBusinessLogic.calculateYearlySalary(employee); assertEquals(96000 , salary, 0.0 ); } }
TestEmployeeDetails 是用来测试 EmpBusinessLogic 类的方法的,它
现在让我们在 C:\ > JUNIT_WORKSPACE 路径下创建一个名为 TestRunner.java 的类来执行测试案例类
1 2 3 4 5 6 7 8 9 10 11 12 13 import org.junit.runner.JUnitCore;import org.junit.runner.Result;import org.junit.runner.notification.Failure;public class TestRunner { public static void main (String[] args) { Result result = JUnitCore.runClasses(TestEmployeeDetails.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } }
用javac编译 Test case 和 Test Runner 类
1 2 C:\JUNIT_WORKSPACE>javac EmployeeDetails.java EmpBusinessLogic.java TestEmployeeDetails.java TestRunner.java
现在运行将会运行 Test Case 类中定义和提供的测试案例的 Test Runner
1 C:\JUNIT_WORKSPACE>java TestRunner
检查运行结果