hamcrest: how to match array is subset of another array?
Asked Answered
K

3

17

Given that:

int[] a = {1, 2, 3, 4};
int[] b = {1, 2, 3, 4, 5};

How to asser that "a" is a subset of "b" using hamcrest matchers?

The following works

assertThat(Arrays.asList(b), hasItems(a));

But since I am creating "a" from "b", I would prefer to apply the asserts on "a" as the value. Something like

assertThat(a, isSubsetOf(b));

Additionally it is preferable to avoid converting the array to a list.

Keeshakeeshond answered 24/11, 2014 at 6:57 Comment(0)
B
26

You can use a combination of the Every and IsIn matcher:

assertThat(Arrays.asList(a), everyItem(in(b)));

This does check if every item of a is contained in b. Make sure a and b are of type Integer[] otherwise you might get unexpected results.

If you are using an older version of hamcrest (for example 1.3) you can use the following:

assertThat(Arrays.asList(a), everyItem(isIn(b)));

In the latest version isIn is deprecated in favor of in.

Bettis answered 24/11, 2014 at 18:56 Comment(3)
The above is a great find. The only issue would be if duplicates need to be supported. If a contains two 3 values but b only contains one, the above would give a false positive.Nigger
@JohnB I got the impression that the OP doesn't care about those duplicates because of the suggestion to use assertThat(Arrays.asList(b), hasItems(a)) which doesn't handle this case either. But you are absolutely right if you do care you have to write your own more sophisticated matcher like @kmmanu suggested.Bettis
This works for me. The important thing is to check if its a subset.For now i will ignore the duplicates.Keeshakeeshond
I
2

Create your own custom matcher by extending org.hamcrest.TypeSafeMatcher and use it in the assertThat() method. You can refer the code of org.hamcrest.collection.IsArrayContaining and create your own matcher

Icecold answered 24/11, 2014 at 8:17 Comment(1)
yeah, if there is isn't a option already available with hamcrest.Keeshakeeshond
J
1

If assertj is an option for you:

    assertThat(b).contains(a); // order doesn't matter
    assertThat(b).containsSequence(a); // order matters
Jiggermast answered 8/6, 2016 at 6:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.