4

在使用 AssertJ 的测试类中,我的代码类似于以下内容:

public void someTest() {
    assertThat(getNames()).has(sameNamesAs(getExpectedNames()));
    assertThat(getNames()).doesNotHave(sameNamesAs(getOtherNames()));
}

private List<String> getNames() {
    return null;
}
private List<String> getExpectedNames() {
    return null;
}
private List<String> getOtherNames() {
    return null;
}

private Condition<List<String>> sameNamesAs(List<String> rhs) {
    return new Condition<List<String>>("same names as " + rhs) {
        @Override
        public boolean matches(final List<String> lhs) {
            return lhs.containsAll(rhs) && rhs.containsAll(lhs);
        }
    };
}

has我在调用and时收到编译错误doesNotHave

has/doesNotHave
(org.assertj.core.api.Condition<? super java.util.List<? extends java.lang.String>>)
in AbstractListAssert cannot be applied
to
(org.assertj.core.api.Condition<java.util.List<java.lang.String>>).

我是 Java 新手,但我不明白这个问题:是和extendsjava.util.List的超类型,不是吗?java.util.Listjava.lang.Stringjava.lang.String

4

1 回答 1

3

在您的情况下,hasanddoesNotHave方法采用Condition<? super List<? extends T>条件,而不是Condition<? super List<T>>您从Condition<List<T>> sameNamesAs方法返回的 a 。

您需要一个类型的实例Condition<List<? extends String>>(它是原始类型的子类Condition<? super List<? extends String>>):

private Condition<List<? extends String>> sameNamesAs(List<String> rhs) {
    return new Condition<List<? extends String>>("same names as " + rhs) { ... };
}

我试图用以下片段来说明这一点:

List<String> list = getNames();

// ELEMENT = String, ACTUAL = List<? extends ELEMENT>
ListAssert<String> assertThat = assertThat(list);

// by the signature, we have to pass Condition<? super ELEMENT> or Condition<? super ACTUAL>
// Condition<? super ACTUAL> = Condition<? super List<? extends String>>
Condition<List<? extends String>> condition = sameNamesAs(list);

// Condition<List<? extends String>> extends Condition<? super List<? extends String>>
assertThat.has(condition);
于 2016-12-13T16:35:50.380 回答