【问题标题】:Hamcrest matcher fails to match Boolean type propertyHamcrest 匹配器无法匹配布尔类型属性
【发布时间】:2016-02-24 03:28:03
【问题描述】:

A;

public class A {
    Integer value;
    Integer rate;
    Boolean checked;
}

我正在构建一个这样的自定义匹配器;

Matchers.hasItems(allOf( hasProperty("value", equalTo(value)), hasProperty("rate", equalTo(rate))))

检查A 列表中是否包含"value" == value && "rate" == rate 列表

我遇到的问题是,当我将 Boolean 类型属性 checked 作为此 Matcher 的约束时,它总是会失败并显示错误消息 property "checked" is not readable

Matchers.hasItems(allOf( hasProperty("value", equalTo(value)), hasProperty("rate", equalTo(rate)), hasProperty("checked", equalTo(checked))))

是否与布尔类型字段的 getter 方法有某种关系?前缀是 is 而不是 get,如果不是 boolean 而是 Boolean,可能是 Hamcrest 无法使用 is 前缀作为 getter输入字段。

另外,我应该补充一点,我无法修改类A 的结构,因此我被Boolean 类型字段卡住了。

【问题讨论】:

    标签: java matcher hamcrest


    【解决方案1】:

    没有人回答这个问题,但是我已经实现了我自己的 HasPropertyWithValue 类,并在 propertyOn 方法中进行了这个小修改,其中生成了给定 bean 和属性名称的 PropertyDescriptor

    private Condition<PropertyDescriptor> propertyOn(T bean, Description mismatch) {
        PropertyDescriptor property = PropertyUtil.getPropertyDescriptor(propertyName, bean);
        if (property != null) {
            if (property.getReadMethod() == null && property.getPropertyType().equals(Boolean.class)) {
                String booleanGetter = "is" propertyName.substring(0, 1).toUpperCase() propertyName.substring(1);
                for(Method method : bean.getClass().getDeclaredMethods()) {
                    if (method.getName().equals(booleanGetter)) {
                        try {
                            property.setReadMethod(method);
                        } catch (IntrospectionException e) {
                            throw new IllegalStateException("Cannot set read method" e);
                        }
                    }
                }
            }
        } else {
            mismatch.appendText("No property \"" + propertyName + "\"");
            return notMatched();
        }
    
        return matched(property, mismatch);
    }
    

    wherePropertyDescriptor创建后,where is has null readMethod。我使用 Java Reflection 来获取以 is 前缀开头的正确布尔 getter 方法,并将其作为 readMethod 添加到属性中。这已经解决了这个问题,但是以如此丑陋的方式。

    我还在 GitHub 中为 Hamcrest 项目创建了拉取请求; https://github.com/hamcrest/JavaHamcrest/pull/136

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 2018-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多