Java JUnit Tutorial - JUnit Test








The following code shows how to use JUnit to test POJO class, Business logic class.

POJO class

The following code is a POJO class for Employee.

public class Employee {
/* ww w  .jav a  2s. c o  m*/
   private String name;
   private double salary;
   private int age;
   
   /**
   * @return the name
   */
   public String getName() {
      return name;
   }
   /**
   * @param name the name to set
   */
   public void setName(String name) {
      this.name = name;
   }
   /**
   * @return the monthlySalary
   */
   public double getSalary() {
      return salary;
   }
   /**
   * @param monthlySalary the monthlySalary to set
   */
   public void setSalary(double s) {
      this.salary = s;
   }
   /**
   * @return the age
   */
   public int getAge() {
      return age;
   }
   /**
   * @param age the age to set
   */
   public void setAge(int age) {
   this.age = age;
   }
}




Business Class

The following is the business class which calculate the salary for a year.


public class EmpBusinessLogic {
   // Calculate the yearly salary of employee
   public double calculateYearlySalary(Employee employee){
      double yearlySalary=0;
      yearlySalary = employee.getSalary() * 12;
      return yearlySalary;
   }
}




Run

Here is the code to run the test case.

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
/*from www . j a  v a 2s  . co  m*/
public class Main {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}

The code above generates the following result.