Skip to content

Chaining-friendly assertion that all elements are equal #4302

Description

@voddan

Feature summary

Provide a chaining-friendly way to assert that all elements are the same:

assertThat(list).allElementsTheSame();

The current best-practice requires using allMatch() and referencing the first element of the list:
assertThat(list).allMatch(e -> e.equals(list.get(0));. However that patter falls short in more complex use cases where the list is produced by filteredOn() and extracting() sequences and cannot be easily referenced.

Example

My current real-world test that verifies that the output table is aligned:

List<String> dataLines = Arrays.stream(output.split("\n"))
	.filter(s -> s.contains("|"))
	.toList();

assertThat(dataLines)
		.hasSize(20)
		.allMatch(s -> s.matches(".* \\| .* --- \\w+"));

List<int[]> pipePositions = dataLines.stream()
	.map(s -> new int[] {s.indexOf('|'), s.indexOf("---")})
	.toList();

assertThat(pipePositions)
		.allMatch(p -> Arrays.equals(p, pipePositions.get(0)));

Note how I cannot join those 2 checks into one because i have to reference the first element.

How it could look like:

assertThat(output.split("\n"))
        .filteredOn(s -> s.contains("|"))
        .hasSize(20)
        .allMatch(s -> s.matches(".* \\| .* --- \\w+"))
        .extracting(s -> new int[] {s.indexOf('|'), s.indexOf("---")})
        .allElementsTheSame()

Special Consideration

As shown in my example, sometimes equals() check on elements is not adequate and a special check is needed (for example Arrays.equals()).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions