Hamcrest 匹配器无法匹配布尔类型 属性

Hamcrest matcher fails to match Boolean type property

对于class 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))))

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

此外,我应该补充一点,我无法修改 class A 的结构,因此我只能使用 Boolean 类型的字段。

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

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);
}

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

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