0

I'm writing simple test which checks method returning some of interface beneath Collection. I'm trying to abstract internal representation of this collection as much as possible, so that this test will pass in both cases: when method returns List and Set.

The Set is supposed to be ordered (LinkedHashSet or LinkedHashMapbacked Set) so I've got to test order too. So generally I'd like to write test like this:

assertThat(returnedList, containsOrdered('t1", "t2", "t3"));

which will fail iff both collections aren't "the same" (i.e. the same values in the same ordering).

I've found Hamcrest library to be useful in this case, however I'm stuck in it's documentation. Any help would be appreciated, however I'll try to avoid writing CollectionTestUtil or my own Hamcrest Matcher if it's possible.

Mateusz Chromiński
  • 2,742
  • 4
  • 28
  • 45

2 Answers2

1

JUnit has the org.junit.Assert that contains multiple assertArrayEquals-implementations for different types, so you could do something like:

    Collection<String> returnedList = new ArrayList<String>(); //Replace with call to whatever returns the ordered collection       
    Assert.assertArrayEquals(new Object[]{"t1", "t2", "t3"}, returnedList.toArray());
esaj
  • 15,875
  • 5
  • 38
  • 52
1

You're nearly there.

assertThat(returnedList, contains("t1", "t2", "t3"))

will do it. Compare with containsInAnyOrder.

Kkkev
  • 4,716
  • 5
  • 27
  • 43
  • Could you provide full package and class path to this contains method? Are you using assertThat from JUnit or from Hamcrest? Is it any difference? – Mateusz Chromiński Apr 07 '12 at 19:29
  • I have had wrong version of hamcrest library, since I was pulling hamcrest-all dependency. I fixed it, together with junit overlapping troubles (there is junit-dep artifact which doesn't provide hamcrest, so there is possibility to add full hamcrest support). Thanks for your help – Mateusz Chromiński Apr 10 '12 at 08:58