Monday 19 March 2018

Hamcrest: sameInstance: objects equality checker

By using ‘sameInstance’ method you can check whether two reference variables point to same object or not. It uses ‘==’ operator to check objects equality.

For example,
Employee emp1 = new Employee(1, "Hari", 5.6);
Employee emp2 = new Employee(1, "Hari", 5.6);
Employee emp3 = emp1;

sameInstance method treats emp1 and emp3 as equal, where as (emp1, emp2) are not equal

Find the below working application.

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.sameInstance;

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 not equal", emp1, sameInstance(emp2));
  assertThat("emp1 and emp3 are equal", emp1, sameInstance(emp3));

 }
}





Previous                                                 Next                                                 Home

No comments:

Post a Comment