hc0re
hc0re

Reputation: 1986

Unit test of a list sorting implementation?

I am currently writing a unit test that is checking if a method is correctly sorting a list.

The sorting method is overrding a compare method from the clas Comparator and is sorting the list using Collections.sort().

It may not be a technical question, but I am looking for a way to use JUnit's assertions to check if the list is correctly sorted...

The list is sorted by an inner parameter of the type it is holding, let me call it id. So when the list contains 3 items with ID's: 3,1,2 - it shall sort them as 1,2,3.

Long expected1 = listOfObjects.get(0).getId()
Long expected2 = listOfObjects.get(1).getId()
Long expected3 = listOfObjects.get(2).getId()

And then using asserions on those Long objects ain't looking clean nor clever. I am looking for an idea how to cleanly and cleverly test this case, but I'm out of ideas...

Upvotes: 4

Views: 6466

Answers (2)

Jean Logeart
Jean Logeart

Reputation: 53819

IMO, you should just unit test the compare method your wrote. Collections.sort() has already been heavily tested!

Just have one simple final test to make sure that Collections.sort() is properly called by the method you wrote:

private final MyComparator comparator = new MyComparator();

@Test
public greaterTest() {
    MyObject o1 = new MyObject(2);
    MyObject o2 = new MyObject(1);
    int c = comparator.compare(o1, o2);
    // assert that c is > 0
}

@Test
public lowerTest() {
    MyObject o1 = new MyObject(1);
    MyObject o2 = new MyObject(2);
    int c = comparator.compare(o1, o2);
    // assert that c is < 0
}

@Test
public equalTest() {
    MyObject o1 = new MyObject(2);
    MyObject o2 = new MyObject(2);
    int c = comparator.compare(o1, o2);
    // assert that c is == 0
}

@Test
public sortTest() {
    List<MyObject> os = // ...
    // call to the function that makes the call to Collections.sort
    List<MyObject> expected = // sorted version of os
    // assert that the sorted list is equal to the expected one
}

Upvotes: 5

Jaroslaw Pawlak
Jaroslaw Pawlak

Reputation: 5578

Have a look on my presentation which contains a point about asserting on lists and shazamcrest library which solves the problem.

With it you can just do assertThat(actual, sameBeanAs(asList(a, b, c))), where a, b and c are your objects of any type.

Upvotes: 1

Related Questions