2016-02-24 99 views
1

對於類A;Hamcrest匹配器無法匹配布爾類型屬性

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 type屬性checked成爲制約這個匹配,它總是失敗的問題錯誤信息msg property "checked" is not readable

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

是它在某種程度上關係到布爾類型字段的getter方法都is前綴,而不是get,並且可以Hamcrest不能用於吸氣is前綴,如果它不是booleanBoolean類型字段。

此外,我應該補充說我無法修改類A的結構,因此我堅持使用Boolean類型字段。

回答

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

凡創作的PropertyDescriptor後,哪裏是具有空readMethod。我使用Java反射來獲取以is前綴開頭的正確布爾型獲取方法,並將其作爲readMethod添加到屬性中。這已經解決了這個問題,但以這樣一種醜陋的方式。

我還在GitHub中爲Hamcrest項目創建了一個拉取請求; https://github.com/hamcrest/JavaHamcrest/pull/136