有没有一个 Hamcrest 匹配器可以检查参数既不是空集合也不是 null?
我猜我总是可以使用
both(notNullValue()).and(not(hasSize(0))
但我在想是否有更简单的方法,而我错过了它。
你可以将 IsCollectionWithSize
和 OrderingComparison
匹配器结合起来使用:
@Test
public void test() throws Exception {
Collection<String> collection = ...;
assertThat(collection, hasSize(greaterThan(0)));
}
当 collection = null
时,您会得到
java.lang.AssertionError:
Expected: a collection with size a value greater than <0>
but: was null
如果使用collection = Collections.emptyList()
,你将得到
java.lang.AssertionError:
Expected: a collection with size a value greater than <0>
but: collection size <0> was equal to <0>
collection = Collections.singletonList("Hello world")
,测试通过。编辑:
刚刚注意到下面的方法不起作用:
assertThat(collection, is(not(empty())));
我越想越觉得,如果您想显式地测试 null,则建议略微修改 OP 所写的陈述。
assertThat(collection, both(not(empty())).and(notNullValue()));
hasSize(greaterThan(0))
和 both(not(empty())).and(notNullValue())
都是不错的方法。 - jhyotmyResponse.body(myArrayAttr, either(empty()).or(nullValue()));
- TheBakkerimport static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
assertThat(collection, anyOf(nullValue(), empty()));
如我在评论中提到的那样,collection != null
和size != 0
的逻辑等价于size > 0
,这意味着集合不为null。表达size > 0
的更简单的方法是集合中存在(任意)元素X
。以下是一个可行的代码示例。
import static org.hamcrest.core.IsCollectionContaining.hasItem;
import static org.hamcrest.CoreMatchers.anything;
public class Main {
public static void main(String[] args) {
boolean result = hasItem(anything()).matches(null);
System.out.println(result); // false for null
result = hasItem(anything()).matches(Arrays.asList());
System.out.println(result); // false for empty
result = hasItem(anything()).matches(Arrays.asList(1, 2));
System.out.println(result); // true for (non-null and) non-empty
}
}
size >= 0
。 - mikeassertThat( metadata, either( is( empty() ) ).or( is( nullValue() ) ) );
- AbdullassertTrue(CollectionUtils.isNotEmpty(collectioin))
。CollectionUtils
是Apache Commons Lang类。 - DwB