2017-07-18 73 views
0

我有串的隊列,我想2級的匹配在一個斷言 結合(簡化)的代碼是這樣的編譯錯誤匹配器

Queue<String> strings = new LinkedList<>(); 
    assertThat(strings, both(hasSize(1)).and(hasItem("Some string"))); 

但是當我編譯我得到以下信息:

incompatible types: no instance(s) of type variable(s) T exist so that org.hamcrest.Matcher<java.lang.Iterable<? super T>> conforms to org.hamcrest.Matcher<? super java.util.Collection<? extends java.lang.Object>> 
  • hasItem返回Matcher<Iterable<? super T>>
  • hasSize返回Matcher<Collection<? extends E>>

我該如何解決這個問題?

回答

1

兩者的匹配器必須符合...

Matcher<? super LHS> matcher 

...其中LHS是Collection<?>因爲stringsCollection<?>

在您的代碼hasSize(1)Matcher<Collection<?>>hasItem("Some string")Matcher<Iterable<? super String>>因此編譯錯誤。

此示例使用一個組合匹配,這是因爲編譯雙方的匹配地址的集合...

assertThat(strings, either(empty()).or(hasSize(1))); 

但是考慮both()方法簽名,你不能合併hasSize()hasItem()

可組合的匹配只是短切所以也許你可以用兩個斷言替換爲:

assertThat(strings, hasSize(1)); 
assertThat(strings, hasItem("Some string")); 
相關問題