Thursday, 5 April 2018

Hamcrest: any: Match an object that is instance of class

By using ‘any’ method, you can create a matcher that is used to match any object that is of given type.

Ex
Employee emp1 = new Employee(1, "Krishna", 12345.6);
assertThat(emp1, any(Employee.class));

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

import org.junit.Test;

import com.sample.model.Employee;

public class TestApp {

 @Test
 public void testmethod() {
  Employee emp1 = new Employee(1, "Krishna", 12345.6);
  assertThat(emp1, any(Employee.class));
 }
}

Previous                                                 Next                                                 Home

No comments:

Post a Comment