Hamcrest hasItem在ArrayList中不匹配

时间:2014-03-24 09:25:22

标签: java unit-testing junit hamcrest

我目前正在测试hasItem() Matcher,但无济于事。请参阅以下示例代码:

List<String> list = new ArrayList<String>();

list.add("1");
list.add("2");
list.add("3");

org.junit.Assert.assertThat(list, hasItem("3"));

它产生

java.lang.NoSuchMethodError: org.hamcrest.Matcher.describeMismatch(Ljava/lang/Object;Lorg/hamcrest/Description;)V
    at org.hamcrest.core.IsCollectionContaining.matchesSafely(IsCollectionContaining.java:31)
    at org.hamcrest.core.IsCollectionContaining.matchesSafely(IsCollectionContaining.java:14)
    at org.hamcrest.TypeSafeDiagnosingMatcher.matches(TypeSafeDiagnosingMatcher.java:55)
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:12)
    at org.junit.Assert.assertThat(Assert.java:865)
    at org.junit.Assert.assertThat(Assert.java:832)
    ...

1 个答案:

答案 0 :(得分:2)

我做了一个本地测试,对我来说使用JUnit-4.11和Hamcrest-Core-1.3非常好:

import java.util.ArrayList;
import java.util.List;

import org.hamcrest.core.IsCollectionContaining;
import org.junit.Test;

public class Example {
    @Test public void test() {
        List<String> list = new ArrayList<String>();
        list.add("1");
        list.add("2");
        list.add("3");
        org.junit.Assert.assertThat(list, IsCollectionContaining.hasItem("3"));
    }
}

你可以像我一样使用相同的库版本和导入再次尝试吗?