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, filter preserve order;
  • sorted establishes order;
  • unordered() and collecting into a HashSet lose order;
  • a parallel forEach doesn't guarantee order, forEachOrdered does;
  • groupingBy gives a HashMap by default: the keys have no order.

The policy:

  1. 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 by in SQL. The order of an unordered select isn't guaranteed either.
  2. If there's no contract, the test shouldn't depend on order: containsExactlyInAnyOrder in AssertJ, and JSONAssert's lenient mode for JSON.
  3. In JSON responses, Map key order: for snapshot tests, ORDER_MAP_ENTRIES_BY_KEYS or SORT_PROPERTIES_ALPHABETICALLY in Jackson.
  4. 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".