Why doesn't this code attempting to use Hamcrest's hasItems compile?

前端 未结 9 1724
耶瑟儿~
耶瑟儿~ 2020-12-03 00:49

Why does this not compile, oh, what to do?

import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.hasItems;

ArrayList<         


        
相关标签:
9条回答
  • 2020-12-03 01:07

    hasItems checks that a collection contains some items, not that 2 collections are equal, just use the normal equality assertions for that. So either assertEquals(a, b) or using assertThat

    import static org.junit.Assert.assertThat;
    import static org.hamcrest.CoreMatchers.is;
    
    ArrayList<Integer> actual = new ArrayList<Integer>();
    ArrayList<Integer> expected = new ArrayList<Integer>();
    actual.add(1);
    expected.add(2);
    assertThat(actual, is(expected));
    

    Alternatively, use the contains Matcher, which checks that an Iterable contains items in a specific order

    import static org.junit.Assert.assertThat;
    import static org.hamcrest.Matchers.contains;
    
    ArrayList<Integer> actual = new ArrayList<Integer>();
    actual.add(1);
    actual.add(2);
    assertThat(actual, contains(1, 2)); // passes
    assertThat(actual, contains(3, 4)); // fails
    

    If you don't care about the order use containsInAnyOrder instead.

    0 讨论(0)
  • 2020-12-03 01:12

    That error message looks like one produced by the javac compiler. I've found in the past that code written using hamcrest just won't compile under javac. The same code will compile fine under, say, the Eclipse compiler.

    I think Hamcrest's generics are exercising corner cases in generics that javac can't deal with.

    0 讨论(0)
  • 2020-12-03 01:12

    You can get this error if you try to replace jUnit's hamcrest with a newer version. For example, using junit-dep together with hamcrest 1.3 requires that use assertThat from hamcrest instead of jUnit.

    So the solution is to use

    import static org.hamcrest.MatcherAssert.assertThat;

    instead of

    import static org.junit.Assert.assertThat;

    0 讨论(0)
提交回复
热议问题