如何使用 junit 的断言检查列表是否仅包含某些不相关的类类型?



希望得到一些帮助,包括Hamcrest和Junit匹配者... :)

我在Eclipse Kepler上使用junit-4.11.jar和hamcrest-core-1.3.jar与sun的jdk 1.6.0_30。

我有一个类,它保存任何未知类型的实例,如下所示:

class UnknownClassHolder {
    private Class<?> clazz;
    public Class<?> getClazz() {
        return clazz;
    } 
    public void setClazz(Class<?> clazz) {
        this.clazz = clazz;
    }
}

克拉兹可以是任何类。

我想让我的 junit 测试是这样的:

class UnknownClassHolderTest {
    @Test
    public void test() {
    ArrayList<UnknownClassHolder> list = new ArrayList<UnknownClassHolder>();
    UnknownClassHolder x = new UnknownClassHolder();
    //lets add an Integer
    x.setClazz(Integer.class);
    list.add(x);
    UnknownClassHolder y = new UnknownClassHolder();
    //lets add a vector
    y.setClazz(Vector.class);
    list.add(y);
    //now check that we added an Integer or a Vector using assertThat
    for (UnknownClassHolder u: list) {
        assertThat(u.getClazz(), anyOf(isA(Integer.class), isA(Vector.class))));
    }
}
}

朱尼特断言不喜欢这样。由于整数和向量类型不通过子/超类相互关联,因此它无法编译:

The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (Class<capture#1-of ?>, AnyOf<Vector>)

除了以下方法之外,还有没有更简洁的方法可以做到这一点:

assertThat(u.getClazz().getName(), either(is(Integer.class.getName())).or(is(Vector.class.getName())));

org.hamcrest.MatcherAssert.assertThat(...)方法中使用Matcher<? super T>而不是Matcher<?>是否有特殊原因?

谢谢。

首先,你应该使用is而不是isA,因为你断言一个类等于另一个类。 isA用于测试对象是否是某个类的实例。其次,我唯一能做的就是强迫编译器将这些视为原始Object

assertThat(u.getClazz(), anyOf(is((Object) Integer.class), is((Object) Vector.class)));

最新更新