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

前端 未结 9 1813
耶瑟儿~
耶瑟儿~ 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 actual = new ArrayList();
    ArrayList expected = new ArrayList();
    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 actual = new ArrayList();
    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.

提交回复
热议问题