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");
        }
    }
  • 相关阅读:
    委托和事件
    Entity Framework应用:导航属性
    Entity Framework应用:根据实体的EntityState状态实现增删改查
    Entity Framework应用:使用EF的DataBase First模式实现数据库的增删改查
    Entity Framework应用:EntityFramework DataBase First模式
    dapper支持操作函数和事物
    单元测试
    IOC容器:Unity
    MVC教程九:异常过滤器
    MVC教程八:缓存过滤器
  • 原文地址:https://www.cnblogs.com/yfzhou528/p/14025228.html
Copyright © 2011-2022 走看看