[英]Hamcrest: how to use either/or combinable matchers with Collections
我正在編寫一些JUnit / Aqruillian類測試來測試Hibernate的一些持久性方法。 因此,我必須從數據庫中獲取許多Hibernate實體列表,並更好地編寫使用JUnit Hamcrest框架的測試。 在這一刻,我想使用可組合的匹配器,特別是一個或多個。 我知道我可以用anyOf()
方法代替它,但是出於代碼可讀性的考慮,我更喜歡可組合的匹配器。 我不明白如何使用or()
方法。 這是一個簡單的示例:
@Test
public void EitherOrMatcherSimple() {
List<String> keywords = Arrays.asList("1");
assertThat(keywords, CombinableMatcher.either(empty()).
or(nullValue()).
or(both(hasItem("1")).and(hasItem("2"))));
}
這樣,我總是會從Eclipse中得到如下錯誤:
The method or(Matcher<? super Collection<? extends Object>>) in the type CombinableMatcher<Collection<? extends Object>> is not applicable for the arguments (CombinableMatcher<Iterable<? super String>>)
因此,我不知道如何使用該方法,無論它期望作為參數是什么。 我知道.or()
方法有Matcher<? super X> other
Matcher<? super X> other
作為參數,這對我來說尚不清楚。
我只知道使用/ &&
和||
引入了一個或兩個方法和/或方法,以更好地編寫和讀取Java條件。 運營商。
有人可以解釋一下嗎?
有時很難組合Hamcrest匹配器的類型安全性。 您的示例就是其中一種情況。 如果沒有顯式強制轉換,甚至可能無法正確處理。
這是擺脫編譯器問題的解決方案:
assertThat(
keywords,
CombinableMatcher.either(empty())
.or(nullValue())
.or((Matcher<? super Collection<?>>) both(hasItem("1")).and(hasItem("2")))
);
如果我正確理解,那么問題是hasItem
簽名太嚴格:
org.hamcrest.Matcher<java.lang.Iterable<? super T>> hasItem(T item)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.