Search code examples
javamavenhamcrestassertthat

How to use Hamcrest's AssertThat for String[]


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?


Solution

  • Use the hasItemInArray matcher:

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

    The hasProperty matcher matches Java Bean properties.