Test if an array contains an element from another array with Hamcrest
Asked Answered
T

1

6

I actually have two types of data:

a = ["1", "2", "3", "3", "5"]
b = ["7", "2"]

given()
       .header("Content-Type", "application/json").
when()
       .post(this.url).
then()
       .statusCode(200)
       .contentType("application/json")
       .body(myPathToData, everyItem(haveOneOrMoreElementFrom(a)));

I would like to test, with Hamcrest, in my body response after my rest-assured request, if b (element received) contains one or more element from a (haveOneOrMoreElementFrom in my example).

Is it also possible to make a function in my body response?

Solution:

I found a possible solution: everyItem(hasItem(isIn(a)))

Traps answered 2/7, 2018 at 6:31 Comment(0)
H
4

I believe that the solution to check if b contains at least one element from a is

assertThat(b, hasItemInArray(isIn(a))); // for arrays

assertThat(b, hasItem(isIn(a))); // for collections

In case of Rest-assured, it would be

...

then()
       .body(pathToData, hasItem(isIn(a)));

In Hamcrest 2 org.hamcrest.Matchers::isIn methods are deprecated, so it is recommended to use is(in(a)) or just in(a) instead.

Homograft answered 2/7, 2018 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.