Friday, 23 March 2018

Hamcrest: equalTo: objects equality using equals method

By using equalTo method, you can create a matcher that check whether this object is logically equal to another object. It uses equals method to check equality of object.

Employee.java
package com.sample.model;

public class Employee {
 private int id;
 private String name;
 private Double experience;

 public Employee(int id, String name, Double experience) {
  this.id = id;
  this.name = name;
  this.experience = experience;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public double getExperience() {
  return experience;
 }

 public void setExperience(double experience) {
  this.experience = experience;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + id;
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Employee other = (Employee) obj;
  if (id != other.id)
   return false;
  return true;
 }

}

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

import org.junit.Test;

import com.sample.model.Employee;

public class TestApp {

 @Test
 public void testmethod() {
  Employee emp1 = new Employee(1, "Hari", 5.6);
  Employee emp2 = new Employee(1, "Hari", 5.6);
  Employee emp3 = emp1;

  assertThat("emp1 and emp2 are equal", emp1, equalTo(emp2));
  assertThat("emp1 and emp3 are equal", emp1, equalTo(emp3));

 }
}





Previous                                                 Next                                                 Home

No comments:

Post a Comment