Skip to content

Compare array elements regardless of order #44

@orangain

Description

@orangain

Motivation

There is a case when we want to compare JSON arrays regardless of their order. For example, an API for testing might return items in no guaranteed order.

Related work

AssertJ

AbstractIterableAssert#containsExactlyInAnyOrder provides comparison regardless of order.

Verifies that the actual group contains exactly the given values and nothing else, in any order.

 Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya, vilya);

 // assertion will pass
 assertThat(elvesRings).containsExactlyInAnyOrder(vilya, vilya, nenya, narya);

 // assertion will fail as vilya is contained twice in elvesRings.
 assertThat(elvesRings).containsExactlyInAnyOrder(nenya, vilya, narya);

Karate

Assertion match contains only provides comparison regardless of order.

For those cases where you need to assert that all array elements are present but in any order you can do this:

* def data = { foo: [1, 2, 3] }
* match data.foo contains 1
* match data.foo contains [2]
* match data.foo contains [3, 2]
* match data.foo contains only [3, 2, 1]
* match data.foo contains only [2, 3, 1]
# this will fail
# * match data.foo contains only [2, 3]

In addition, assertion match contains only deep provides order insensitive comparison for the deep array.

This is exactly like match == but the order of arrays does not matter. All arrays no matter the "depth" will be checked in this way.

* def response = { foo: [ 'a', 'b' ] }
* match response contains only deep { foo: [ 'b', 'a' ] }

Solution

To be determined. Ideas are welcome!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions