zoukankan      html  css  js  c++  java
  • 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");
        }
    }
  • 相关阅读:
    @PathVariable和@RequestParam的区别,@SessionAttributes
    forward和redirect的区别
    JSP页面的静态包含和动态包含
    ConcurrentHashMap源码解析
    Jdk1.6 JUC源码解析(1)-atomic-AtomicXXX
    最小生成树
    tomcat启动项目内存溢出问题
    强引用,弱引用,4种Java引用浅解(涉及jvm垃圾回收)
    CXF 在WAS上报Unmarshalling Error的问题
    CXF处理Date类型的俩种方式
  • 原文地址:https://www.cnblogs.com/yfzhou528/p/14025228.html
Copyright © 2011-2022 走看看