简体   繁体   中英

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?

Use the hasItemInArray matcher:

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

The hasProperty matcher matches Java Bean properties.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM