Arc-E-Tect
Arc-E-Tect

Reputation: 135

Matching json values in an array using spring restdocs in random order

I am using Spring RestDocs to validate my REST APIs.

One API is returning an array of generated values based on some input. I want to verify that the generated values in the response are correct.

A response could be:

{ "hybrids": ["horsephant", "pussydog", "tigerbird"]

Since the order of the values is not relevant, the next call to the API could result in:

{ "hybrids": ["pussydog", "horsedonkey", "tigerbird"]

I am using the following snippet in my RestDoc test:

.jsonPath("$.hybrids[0]").isEqualTo("pussydog")             .jsonPath("$.hybrids[1]").isEqualTo("horsedonkey")              .jsonPath("$.hybrids[2]").isEqualTo("tigerbird");

This only results in a pass when the order is accidently like that. How can I remove the order of the items and have both responses result in a pass of the test?

Thanks

Upvotes: 0

Views: 55

Answers (1)

Gwaptiva
Gwaptiva

Reputation: 395

The answer lies in using the Hamcrest matchers in your jsonPath check:

.jsonPath("$.hybrids[*]", CoreMatchers.hasItem("pussydog"))
.jsonPath("$.hybrids[*]", CoreMatchers.not(CoreMatchers.hasItem("banana"))

and so forth (probably want to statically import CoreMatchers.*, but that's up to you)

Upvotes: 1

Related Questions