Program: Assertion method Assert.assertEquals() example.
Java Class: org.junit.Assert
Assert class provides a set of assertion methods useful for writing tests.
Assert.assertEquals() methods checks that the two objects are equals or not. If they are not,
an AssertionError without a message is thrown. Incase if both expected and actual values are null, then this method
returns equal. In the below example, the first Test (mySimpleEqualsTest()) compares two strings. The second test (myObjectEqualsTest())
we are comparing two different user defined objects. The assertEquals() method calls equals method on each object to check equality.
package com.java2novice.junit.tests;
import org.junit.Test;
import com.java2novice.junit.samples.Employee;
import static org.junit.Assert.*;
public class MyAssertEqualsTest {
@Test
public void mySimpleEqualsTest(){
String expectedName = "Nattu";
assertEquals(expectedName, Employee.getEmpNameWithHighestSalary());
}
@Test
public void myObjectEqualsTest(){
Employee expectedEmpObj = new Employee(1, "Nattu", 15000);
assertEquals(expectedEmpObj, Employee.getHighestPaidEmployee());
}
}
|
package com.java2novice.junit.samples;
import java.util.ArrayList;
import java.util.List;
public class Employee {
private String name;
private int empId;
private int salary;
public Employee(int id, String name, int sal){
this.empId = id;
this.name = name;
this.salary = sal;
}
public boolean equals(Object obj){
Employee emp = (Employee) obj;
boolean status = false;
if(this.name.equalsIgnoreCase(emp.name)
&& this.empId == emp.empId
&& this.salary == emp.salary){
status = true;
}
return status;
}
public static String getEmpNameWithHighestSalary(){
/**
* logic to get Highest paid employee
*/
return "Nattu";
}
public static Employee getHighestPaidEmployee(){
/**
* hiding logic to get highest paid employee
*/
return new Employee(1, "Nattu", 15000);
}
public int hashCode(){
return this.empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
|
|