By using ‘lessThanOrEqualTo’ method, you can create a matcher of Comparable object that matches when the examined object is less than or equal to the specified value.
Ex
assertThat("1 is
assertThat("1 is
TestApp.java
package com.sample.tests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import org.junit.Test;
public class TestApp {
@Test
public void testmethod() {
assertThat("1 is , 1, lessThanOrEqualTo(1));
assertThat("1 is , 1, lessThanOrEqualTo(2));
}
}
As you see the signature of lessThanOrEqualTo method, you can call this method on any Comparable instances.
public static > org.hamcrest.Matcher lessThanOrEqualTo(T value)
Let us try to compare whether one Employee less than or equal to other based on their experience in the organization.
public Class Employee Implements Comparable {
....
....
public int compareTo(Employee emp) {
if (emp == null)
return 1;
return this.experience.compareTo(emp.experience);
}
}
Since Employee class is implementing Comparable interface, we can use lessThanOrEqualTo matcher to compare two employee objects.
Ex
Employee emp1 = new Employee(1, "Krishna", 5.6);
Employee emp2 = new Employee(2, "Chamu", 6.1);
Employee emp3 = new Employee(3, "Gopi", 5.6);
assertThat("emp1 is
assertThat("emp3 is
Find the below working application.
Employee.java
package com.sample.model;
public class Employee implements ComparableEmployee> {
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;
}
public int compareTo(Employee emp) {
if (emp == null)
return 1;
return this.experience.compareTo(emp.experience);
}
}
TestApp.java
package com.sample.tests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import org.junit.Test;
import com.sample.model.Employee;
public class TestApp {
@Test
public void testmethod() {
Employee emp1 = new Employee(1, "Krishna", 5.6);
Employee emp2 = new Employee(2, "Chamu", 6.1);
Employee emp3 = new Employee(3, "Gopi", 5.6);
assertThat("emp1 is , emp1, lessThanOrEqualTo(emp2));
assertThat("emp3 is , emp3, lessThanOrEqualTo(emp2));
}
}
Previous Next Home
This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here