By
using ‘greaterThan’ method, you can create a matcher of Comparable object that
matches when the examined object is greater than the specified value.
Employee.java
Ex
assertThat("2
greater than 1", 2, greaterThan(1));
TestApp.java
package com.sample.tests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import org.junit.Test; public class TestApp { @Test public void testmethod() { assertThat("2 greater than 1", 2, greaterThan(1)); } }
As
you see the signature of greaterThan method, you can call this method on any Comparable
instances.
public static <T
extends java.lang.Comparable<T>> org.hamcrest.Matcher<T>
greaterThan(T value)
Let
us try to compare whether two employees greater than or not based on their
experience in the organization.
public
class Employee implements Comparable<Employee> {
....
....
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 greaterThan
matcher to compare two employee objects.
Employee
emp1 = new Employee(1, "Krishna", 5000.56);
Employee
emp2 = new Employee(2, "Chamu", 7090.57);
assertThat("emp2
must > emp1", emp2, greaterThan(emp1));
Find
the below working application.
package com.sample.model; public class Employee implements Comparable<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; } 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.greaterThan; import org.junit.Test; import com.sample.model.Employee; public class TestApp { @Test public void testmethod() { Employee emp1 = new Employee(1, "Krishna", 5000.56); Employee emp2 = new Employee(2, "Chamu", 7090.57); assertThat("emp2 must > emp1", emp2, greaterThan(emp1)); } }
No comments:
Post a Comment