Here we will see one complete example of JUnit testing using POJO class, Business logic class, and a test class, which will be run by the test runner.
Create EmployeeDetails.java which is a POJO class.
Create a file called EmpBusinessLogic.java
which contains the business logic.
Create a file called TestEmployeeDetails.java
which contains the test cases to be tested.
Next, create a java class filed named TestRunner.java to execute test case(s).
Compile the test case and Test Runner classes using javac.
Create EmployeeDetails.java which is a POJO class.
public class EmployeeDetails { private String name; private double monthlySalary; private int age;
generate get and set
Create a file called EmpBusinessLogic.java
which contains the business logic.
public class EmpBusinessLogic { // Calculate the yearly salary of employee public double calculateYearlySalary(EmployeeDetails employeeDetails) { double yearlySalary = 0; yearlySalary = employeeDetails.getMonthlySalary() * 12; return yearlySalary; } // Calculate the appraisal amount of employee public double calculateAppraisal(EmployeeDetails employeeDetails) { double appraisal = 0; if(employeeDetails.getMonthlySalary() < 10000){ appraisal = 500; }else{ appraisal = 1000; } return appraisal; } }
which contains the test cases to be tested.
public class TestEmployeeDetails { EmpBusinessLogic empBusinessLogic = new EmpBusinessLogic(); EmployeeDetails employee = new EmployeeDetails(); //test to check appraisal @Test public void testCalculateAppriasal() { employee.setName("Rajeev"); employee.setAge(25); employee.setMonthlySalary(8000); double appraisal = empBusinessLogic.calculateAppraisal(employee); assertEquals(500, appraisal, 0.0); } // test to check yearly salary @Test public void testCalculateYearlySalary() { employee.setName("Rajeev"); employee.setAge(25); employee.setMonthlySalary(8000); double salary = empBusinessLogic.calculateYearlySalary(employee); assertEquals(96000, salary, 0.0); } }
Next, create a java class filed named TestRunner.java to execute test case(s).
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()); } }
Compile the test case and Test Runner classes using javac.
Verify the output.
true
No comments:
Post a Comment