如何将 Hamcrest 的 AssertThat 用于 String[]

How to use Hamcrest's AssertThat for String[]

所以我一直在四处寻找并试图找到解决这个问题的方法,但我遇到了编译器错误或奇怪的期望或两者兼而有之。 所以我们开始吧:

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"));

所以这段代码编译得很好,但是当我在 Maven 中构建它时,测试失败了,因为:Expected: hasProperty("John"), got:[John]

所以我做了一些查看并检查了人们在这里回答的其他问题,但我遇到了编译错误,我显然做错了 assertThat 但应该如何设置 assertThat?

使用 hasItemInArray 匹配器:

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

hasProperty 匹配器匹配 Java Bean 属性。

如果你想断言数组 fname 包含项目 John 而没有其他你可以使用 IsArrayContainingInOrder 匹配器(Matchers.arrayContaining):

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

如果您只关心 fname 中的至少一项是 John,请按照@hzpz 的建议使用 IsArrayContaining 匹配器 (Matchers.hasItemInArray)。