10. 自定义assertThat中的Matcher函数lt、gt
package lesson10; import org.junit.Test; import static org.hamcrest.CoreMatchers.both; import static org.junit.Assert.assertThat; public class SimpleTest { @Test public void test() { assertThat(1, CompareNumberMatcher.lt(3)); assertThat(10, CompareNumberMatcher.gt(3)); assertThat(5, both(CompareNumberMatcher.gt(3)).and(CompareNumberMatcher.lt(10))); } }
package lesson10; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Factory; public class CompareNumberMatcher<T extends Number> extends BaseMatcher<T> { private final T value; private final Boolean greater; public CompareNumberMatcher(T value, Boolean greater) { this.value = value; this.greater = greater; } @Factory public static <T extends Number> CompareNumberMatcher<T> gt(T value) { return new CompareNumberMatcher<>(value, true); } @Factory public static <T extends Number> CompareNumberMatcher<T> lt(T value) { return new CompareNumberMatcher<>(value, false); } @Override public boolean matches(Object actual) { Class<?> clazz = actual.getClass(); if (clazz == Integer.class) { return greater ? (Integer) actual > (Integer) value : (Integer) actual < (Integer) value; } else if (clazz == Long.class) { return greater ? (Long) actual > (Long) value : (Long) actual < (Long) value; } else if (clazz == Short.class) { return greater ? (Short) actual > (Short) value : (Short) actual < (Short) value; } else if (clazz == Double.class) { return greater ? (Double) actual > (Double) value : (Double) actual < (Double) value; } else if (clazz == Float.class) { return greater ? (Float) actual > (Float) value : (Float) actual > (Float) value; } else if (clazz == Byte.class) { return greater ? (Byte) actual > (Byte) value : (Byte) actual < (Byte) value; } else { throw new AssertionError("The number type [" + clazz + "] not matched..."); } } @Override public void describeTo(Description description) { description.appendText("compare value of two number"); } }