代码之家  ›  专栏  ›  技术社区  ›  Nir Brachel

尝试组合hamcrest匹配器时出现编译错误

  •  0
  • Nir Brachel  · 技术社区  · 7 年前

    我有一个字符串队列,我想在一个断言中组合两个匹配器 (简化的)代码是这样的

        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>>
    • Matcher<Collection<? extends E>>

    我如何解决这个问题?

    1 回复  |  直到 7 年前
        1
  •  2
  •   glytching    7 年前

    两个匹配者都必须符合。。。

    Matcher<? super LHS> matcher
    

    Collection<?> 因为 strings 是一个 集合(<&燃气轮机; .

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