使用 Java 8 将列表对象中的 属性 断言为 null

Assert a property from list object as null using Java 8

这是我的模拟响应,我需要在其中将特定字段(类型)断言为 null。它总是抛出异常

   java.lang.AssertionError: expected null, but was:<[null]>
    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.Assert.failNotNull(Assert.java:755)
    at org.junit.Assert.assertNull(Assert.java:737)
    at org.junit.Assert.assertNull(Assert.java:747)

模拟回复

{
"locations": [
 {
  "type": null,     
  "statusDt": "2018-08-15",
 
   }
  ]  
}

我正在按照以下方式进行断言

    assertNull(locationResponse.getLocations().stream().map(location -> location.getType()).collect(Collectors.toList()));

似乎作为 collect() 操作的结果,您得到一个仅包含一个元素 nullList。 请尝试从该列表中获取第一个元素

assertNull(locationResponse.getLocations().stream().map(location -> location.getType()).collect(Collectors.toList()).get(0));

断言的消息说 null 是预期的,但观察到 [null][null] 是一个包含单个 null 元素的数组。

我认为 collect(Collectors.toList())) 不能 return 一个 null 对象。

你应该写一个像这样的断言来检查所有类型都是 nullassertTrue(locationResponse.getLocations().stream().map(location -> location.getType()).allMatch(type -> type == null));

考虑对每种类型进行断言,例如(工作示例here):

locationResponse.getLocations()
                .stream()
                .map(location -> location.getType())
                .forEach(t -> assertNull(t));