How to use Hamcrest's AssertThat for String[]

1.1k Views Asked by At

So I've been looking around and trying to find a solution to this problem but I'm coming up with either compiler errors or weird expectations or both. So here we go:

this.mockPersonNode.setProperty("fname",new String[] {"John"});
...unrelated code...
//validate traits
final String[] fname = (String[]) groovy.getProperty("firstName");
//This is where my problems lie
assertThat(fname, hasProperty("John"));

So this code compile fine but when I go to build it in Maven the test fails because:Expected: hasProperty("John"), got:[John]

So I did some looking and checked out the other questions people got answered here but I get compile errors, I am clearly doing the assertThat wrong but how should the assertThat be set up?

2

There are 2 best solutions below

0
On BEST ANSWER

Use the hasItemInArray matcher:

assertThat(fname, hasItemInArray("John"));

The hasProperty matcher matches Java Bean properties.

0
On

If you want to assert that array fname contains the item John and nothing else you can use the IsArrayContainingInOrder matcher (Matchers.arrayContaining):

assertThat(fname, arrayContaining("John"));

If you only care that at least one item in fname is John use the IsArrayContaining matcher (Matchers.hasItemInArray) as suggested by @hzpz.