[英]How to use AssertThat to check the property value of objects in a list?
I am to using asserThat to verify properties of objects in an ArrayList.我将使用 asserThat 来验证 ArrayList 中对象的属性。
I am able to use assertThat if none of the objects contains data to be tested but I am not able to figure how to use assertThat if only one of the objects contain data to be tested.如果没有任何对象包含要测试的数据,我可以使用 assertThat 但如果只有一个对象包含要测试的数据,我无法弄清楚如何使用 assertThat。
Sample Code:示例代码:
public class dataNeeded {
String data;
String modifiedDate;
public String getData(){
return data;
}
......
}
public ArrayList<dataNeeded> returnsNeededData(){
...
}
List<dataNeeded> dataToBeTested = returnsNeededData();
dataToBeTested.forEach(data->assertThat(data.getData(), not(equalTo("No"))));
List<dataNeeded> dataToBeTested2 = returnsNeededData();
// I need to verify if one of the objects in this list has it's data as "No"
dataToBeTested.forEach(data->assertThat(data.getData(), ???);
You can map to List<String>
via the following function (uses Java 8 Streams) to extract all data strings您可以通过以下函数(使用 Java 8 Streams)映射到
List<String>
以提取所有数据字符串
private List<String> mapToDataStrings(List<dataNeeded> neededData) {
return neededData.stream()
.map(dataNeeded -> dataNeeded.getData())
.collect(toList());
}
and then use the everyItem
/ hasItem
function in Matchers
to make assertions on the resulting list of strings:然后使用
everyItem
/ hasItem
功能Matchers
,使生成的字符串列表上断言:
List<String> dataToBeTested = mapToDataStrings(returnsNeededData());
assertThat(dataToBeTested, everyItem(not("No")));
List<String> dataToBeTested2 = mapToDataStrings(returnsNeededData());
assertThat(dataToBeTested2, hasItem("No"));
With everyItem
you can assert that every element in the list is not "No" and hasItem
asserts that there is at least one element in the list with value "No".使用
everyItem
您可以断言列表中的每个元素都不是“No”,而hasItem
断言列表中至少有一个值为“No”的元素。
Alternatively you could implement a feature matcher to avoid the mapping function.或者,您可以实现一个特征匹配器来避免映射函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.