2017-07-18 76 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")); 
相关问题