Testing collection equality with ordering

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.

Answers


You're nearly there.

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

will do it. Compare with containsInAnyOrder.


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());

Need Your Help

add two double given wrong result

c# .net floating-point double addition

I'm using the following piece of code and under some mysterious circumstances the result of the addition is not as it's supposed to be:

My Partial Views don't show

.net asp.net-mvc asp.net-mvc-4 partial-views

for the first time I'm using Partial Views. On this page I have a sub menu on the left and based on what is clicked in the menu I need to show a partial view on the right.