Video in progress
Tests pass on a local machine but fail intermittently in CI; the cause turned out to be result order. How does encounter order work in streams, and how do you prevent such flaky tests?
A stream inherits the source's order: a List is ordered, a HashSet and HashMap aren't, and their iteration order depends on the hash, the capacity and the JDK version. If a test relies on order but the code doesn't guarantee it, it is flaky. The solution: if order is part of the contract, make it explicit in code; if not, the test should compare without regard to order.
📖 Answer
The usual case: a service streams from a Set<Tag> or a Map and returns a toList(), and the test does assertEquals(List.of("a", "b", "c"), result). On the local machine the HashSet order happens to match. In CI the order changes because of a different JDK, a different capacity, or because the data was added in a different order.
Another source: Set.of(...) and Map.of(...) have their iteration order shuffled with a random "salt" when the JVM starts. This is deliberate, so that code relying on order breaks sooner. It is stable within one JVM, and different on the next start.
How stream stages affect order:
map,filterpreserve order;sortedestablishes order;unordered()and collecting into aHashSetlose order;- a parallel
forEachdoesn't guarantee order,forEachOrdereddoes; groupingBygives aHashMapby default: the keys have no order.
The policy:
- Is order part of the contract? If the API says "sorted by date", then in the code use
sorted(comparing(...))and, if needed,LinkedHashMap/TreeMap. If it comes from the DB,order byin SQL. The order of an unorderedselectisn't guaranteed either. - If there's no contract, the test shouldn't depend on order:
containsExactlyInAnyOrderin AssertJ, andJSONAssert's lenient mode for JSON. - In JSON responses,
Mapkey order: for snapshot tests,ORDER_MAP_ENTRIES_BY_KEYSorSORT_PROPERTIES_ALPHABETICALLYin Jackson. - Catch flakiness early: run the tests in random order in CI (JUnit 5
MethodOrderer.Random), and sometimes on a different JDK too.
In larger teams I track flaky tests separately (a list of tests that passed on retry). Order-related flakiness often points to a real bug: a client may also be relying on that order, and one day the list in the UI will get shuffled "by itself".
Sign up to mark studied questions and save your progress.