Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit Testing for attribute values within in Stream

This question is related to my previous question at JUnit assertions within in Java 8 stream.

If I have 3 objects, how do I verify the values of the objects' attributes within a stream? My previous question answered how to test for the presence of them, but I now need to test for each individual attribute's value. Can someone give me a code snippet?

like image 752
CNDyson Avatar asked Apr 25 '26 16:04

CNDyson


1 Answers

You can filter the properties by the expected values and count the resulting entries. This number must be equal to the original size.

List<Integer> expected = Arrays.asList(1, 2, 3);
long count = objects.stream()
    .map(MyObject::getId)
    .filter(id -> expected.contains(id.intValue()))
    .count();
Assert.assertEquals(objects.size(), (int) count);

If you want to check all properties in one stream, do it like this:

long count = objects.stream()
    .filter(o-> expectedIds.contains(o.getId().intValue()))
    .filter(o-> expectedNames.contains(o.getName()))
    // and so on
    .count();
like image 156
Stefan Warminski Avatar answered Apr 28 '26 06:04

Stefan Warminski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!