Writing Tests for Java Collection Algorithms with Assertions

Collection algorithms often look too small to deserve dedicated tests. Sorting a list, finding an element with binary search, or removing duplicates may take only a few lines of Java, yet these operations can quietly damage application behaviour when ordering, mutability, null handling, or duplicate values are misunderstood.

Focused tests make those assumptions visible. For developers and test engineers working with Java or Groovy backend services, a good test suite should verify the algorithm’s result, its treatment of boundary cases, and any side effects on the supplied collection. JUnit 5, AssertJ, and property-based techniques provide enough expressive power without turning simple collection logic into an elaborate framework.

Define The Collection Contract First

Before writing assertions, describe what the method promises. A sorting method might return a new list in ascending order, sort the original list in place, preserve duplicate values, and reject null elements. A searching method might return an index, an optional value, or a boolean. Each choice creates different test cases.

For example, this method has a clear contract:

static List<Integer> sortedCopy(List<Integer> input) {
    return input.stream()
            .sorted()
            .toList();
}

Its tests should establish that the result is ordered, the input remains unchanged, duplicates survive, and an empty input produces an empty result. Testing only [3, 1, 2] is insufficient because it says nothing about the collection’s other observable behaviours.

A useful test matrix includes normal data, already ordered data, reverse order, repeated values, one item, no items, negative values, and large values. If the API permits nulls, add explicit null cases. If it does not, assert the documented exception rather than leaving the behaviour accidental.

Assert Sorted Results Clearly

An equality assertion is the simplest way to verify a known sorted sequence:

@Test
void sortsNumbersInAscendingOrder() {
    List<Integer> input = List.of(7, 2, 9, 2, -1);

    List<Integer> result = sortedCopy(input);

    assertThat(result).containsExactly(-1, 2, 2, 7, 9);
    assertThat(input).containsExactly(7, 2, 9, 2, -1);
}

containsExactly checks both values and order, making it stronger than an assertion that merely checks whether all expected values are present. This matters for collection algorithms because ordering is usually the main outcome. It also confirms that duplicate 2 values have not been collapsed.

When the output is too large for a literal expected list, assert general ordering properties. For a list of integers, every item should be less than or equal to the next item. A helper can express that rule:

static void assertSorted(List<Integer> values) {
    for (int i = 1; i < values.size(); i++) {
        assertThat(values.get(i))
                .as("values at indexes %s and %s", i - 1, i)
                .isGreaterThanOrEqualTo(values.get(i - 1));
    }
}

This style produces a useful failure location instead of a vague “expected list differs” message. It is especially helpful for sorting customer records by a field, where the expected order may be generated rather than written manually.

Use a second assertion for permutation behaviour. A sorting algorithm should generally preserve the same elements, including their multiplicity. Comparing frequency maps catches implementations that accidentally drop or duplicate values:

assertThat(result)
        .containsExactlyInAnyOrderElementsOf(input);

That assertion should accompany an order assertion, not replace it. It proves the result contains the right members but does not prove they are sorted.

Test Searching At Boundaries

Searching algorithms need stronger boundary coverage than a single successful lookup. A binary search should be tested for the first element, the last element, a middle element, a missing value below the minimum, a missing value above the maximum, and a missing value between two existing values.

Suppose the implementation returns an index:

static int binarySearch(List<Integer> values, int target) {
    int low = 0;
    int high = values.size() - 1;

    while (low <= high) {
        int middle = (low + high) >>> 1;
        int current = values.get(middle);

        if (current == target) {
            return middle;
        }
        if (current < target) {
            low = middle + 1;
        } else {
            high = middle - 1;
        }
    }
    return -1;
}

The assertions should verify the result’s meaning rather than over-specifying an implementation detail:

@Test
void findsAnExistingValue() {
    List<Integer> values = List.of(1, 4, 8, 12, 19);

    int index = binarySearch(values, 12);

    assertThat(index).isGreaterThanOrEqualTo(0);
    assertThat(values.get(index)).isEqualTo(12);
}

@Test
void reportsMissingValue() {
    List<Integer> values = List.of(1, 4, 8, 12, 19);

    assertThat(binarySearch(values, 10)).isEqualTo(-1);
}

For unique values, asserting the exact index is reasonable. For duplicate values, it may be wrong to require the first or last matching index unless the contract states that behaviour. Instead, assert that the returned index is valid and points to the target.

A sorted search also has a precondition: the input must be ordered according to the same comparator used by the algorithm. Test that precondition if the method validates it. Otherwise, keep invalid-input behaviour out of the contract and avoid asserting an arbitrary result from an unsorted list.

Cover Comparators, Nulls, And Mutability

Collection algorithms frequently become less predictable when a custom comparator is introduced. A test for case-insensitive strings, for example, should verify both the comparator and the algorithm:

@Test
void sortsNamesWithoutConsideringCase() {
    List<String> names = List.of("zoe", "Amelia", "liam");

    List<String> result = names.stream()
            .sorted(String.CASE_INSENSITIVE_ORDER)
            .toList();

    assertThat(result).containsExactly("Amelia", "liam", "zoe");
}

For domain objects, create small fixtures with meaningful fields. Testing Order objects by their total amount should include equal amounts, because equal sort keys raise questions about stability. If the requirement says the original order must be retained for equal keys, assert that explicitly.

Null handling must be deliberate. List.of rejects nulls, while ArrayList permits them. A method may reject null with NullPointerException, place null first, place null last, or support a comparator such as Comparator.nullsLast. Pick one contract and test it directly:

@Test
void placesNullValuesLast() {
    Comparator<String> comparator =
            Comparator.nullsLast(String::compareTo);

    List<String> result = Stream.of("Perth", null, "Sydney")
            .sorted(comparator)
            .toList();

    assertThat(result).containsExactly("Perth", "Sydney", null);
}

Mutability deserves its own assertion. Stream.toList() returns an unmodifiable result in modern Java, whereas Collectors.toList() does not guarantee a particular mutability contract. If callers need to edit the result, test that they can; if the result must be read-only, assert the expected UnsupportedOperationException.

Use Data-Driven And Property-Based Checks

JUnit 5 parameterised tests reduce repetition for related search and sort cases. They are particularly useful for edge values and small collections:

@ParameterizedTest
@CsvSource({
        "1, 0",
        "8, 2",
        "19, 4",
        "10, -1"
})
void searchesSeveralTargets(int target, int expectedIndex) {
    List<Integer> values = List.of(1, 4, 8, 12, 19);

    assertThat(binarySearch(values, target)).isEqualTo(expectedIndex);
}

For a sorting method, @MethodSource can provide lists containing empty input, one value, duplicates, negatives, and reverse order. Keep each case readable; a parameterised test should reveal why a case matters instead of hiding the scenario inside a complicated data builder.

Property-based testing is valuable when the input space is large. With jqwik or QuickTheories, generate arbitrary integer lists and check universal properties: the output is ordered, the output has the same size, and the output contains the same multiset of values as the input. These properties often discover combinations that hand-written examples miss.

Performance assertions should be separate from correctness assertions. A list with one million values can expose an accidental quadratic implementation, but timing tests are sensitive to CI load and virtual machine warm-up. For reliable performance measurement, use JMH. For ordinary unit tests, verify correctness on representative collections and reserve benchmarks for algorithmic claims.

In Australian teams, these tests also help protect services that process local business data: Sydney and Melbourne delivery records may arrive in different input orders, while Brisbane and Perth systems can expose assumptions about sorting or scheduling fields. End-of-financial-year reporting can produce unusually large collections, so a test fixture representing a high-volume batch is useful without making every unit test slow.

Choose Assertions That Explain Failures

A test should tell its maintainer what broke. AssertJ’s fluent assertions are effective for collections because they report missing, unexpected, and misplaced elements. Prefer containsExactly when order matters, containsExactlyInAnyOrderElementsOf when only membership matters, and containsSubsequence when a partial ordering is the contract.

Hamcrest and standard JUnit assertions remain valid choices. The important point is consistency and diagnostic value. Avoid writing a single broad assertion over a complex object if separate assertions can distinguish an incorrect sort key, a lost item, and an unwanted mutation.

The following comparison helps select an assertion style:

Behaviour under test Useful assertion What it verifies
Exact sorted output containsExactly(...) Values, quantity, and order
Same elements after sorting containsExactlyInAnyOrderElementsOf(...) Membership and duplicate counts
Search success isGreaterThanOrEqualTo(0) plus values.get(index) Valid index pointing to target
Search miss isEqualTo(-1) or documented result Missing-value contract
Empty input isEmpty() Safe handling of no elements
Input preservation Assert original list separately No unwanted mutation
Invalid input assertThatThrownBy(...) Documented exception and message

Do not over-test private implementation details such as the number of loop iterations or whether Collections.sort was called. Tests should survive a change from insertion sort to merge sort when the public behaviour remains the same. The exception is a deliberate performance or stability contract, which should be tested through observable outcomes or dedicated benchmarks.

For a practical workflow, start with the contract, add examples for boundaries, then add invariant checks for general behaviour. Run the focused test class locally and in CI, including the same Java version used by the application. A concrete next step is to create a CollectionAlgorithmsTest class with one sorting case, one duplicate-preservation case, and parameterised search cases for the first, last, missing, and empty inputs.