Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hamcrest: how to match array is subset of another array?

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.

like image 510
Kiran Mohan Avatar asked Nov 24 '14 06:11

Kiran Mohan


People also ask

What is a matcher in Hamcrest?

Hamcrest is a framework for writing matcher objects allowing 'match' rules to be defined declaratively. There are a number of situations where matchers are invaluable, such as UI validation or data filtering, but it is in the area of writing flexible tests that matchers are most commonly used.


2 Answers

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.

like image 126
eee Avatar answered Oct 16 '22 23:10

eee


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

like image 2
Manu Avatar answered Oct 16 '22 22:10

Manu