Philippe Carriere Philippe Carriere - 3 months ago 19
Java Question

How to test the ordering of elements in a Collection in JUnit test?

I want to verify my ordering algorithm of a collection in Java with JUnit tests. If I input "B","C","A" into a collection and want it sorted (alphabetically for example), what is the proper way to test this with JUnit ?

I implemented the Comparable interface and want to make sure my sorting is working.

I suppose this question could be broaden beyond Java or JUnit to general testing in any language.

Answer

I would create another collection with the values in the expected order, and then just check that the results match.

But to be honest, if you're just trying to check your implementation of IComparable and not some sort algorithm, I would just make assertions about the results of calling compareTo. It'll be simpler to write the tests and much simpler to understand any failures.

(If a sorting test fails, that would just mean that one of the many comparisons did the wrong thing. It wouldn't help you work out which comparison did the wrong thing.)