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");
        }
    }
  • 相关阅读:
    ARP投毒攻击
    sniffer简单使用
    MAC泛洪攻击
    又是一题反序列化了解一下???
    关于parse_str变量覆盖分析
    超级ping(多线程版)
    文本输入框input将输入转换为统一大小写
    通俗易懂JSONP讲解
    通俗易懂JSONP讲解
    Fastjson主要接口和类库说明
  • 原文地址:https://www.cnblogs.com/yfzhou528/p/14025228.html
Copyright © 2011-2022 走看看