简体   繁体   中英

JUnit assertions within in Java 8 stream

Say I have three objects that I save to the database and set the db generated ID into. I don't know the order of the objects returned from the method saveToDb . But I want to junit test that those generated IDs are there. How do I do that within in stream? I want to do something like this:

List<MyObject> myObjects = getObjects();
numRecords = saveToDb(myObjects); // numRecords=3
List<Integer> intArray = Arrays.asList(1, 2, 3);
intArray.stream()
  .forEach(it -> myObjects.stream()
    .filter(it2 -> it2.getId().equals(it))
    .????

But I'm not sure where my assertEquals() would go in a statement like this. Or is my approach all wrong? I know I could use a simple for-loop, but I like the elegance of streams. Additionally, is there a way to dynamically create the intArray, in case I have more than 3 myObjects?

It seems (if i understood correctly), how about something like this:

 boolean result = Arrays.asList(1, 2, 3).stream()
            .allMatch(i -> objects
                .stream()
                .map(MyObject::getId)
                .filter(j -> j == i).findAny().isPresent());
    Assert.assertTrue(result);

So you basically want to check whether a MyObject instance was assigned an ID? Is the equalness to the IDs in the array from any importance?

If not:

List<MyObject> objects = getObjects();
saveToDb(objects);
objects.stream().map(MyObject::getId).forEach(Assert::assertNotNull);

Assuming there is a "getId" Method on MyObject of course.

Just a little supplement for your additional question:

Additionally, is there a way to dynamically create the intArray, in case I have more than 3 myObjects?

Yes you can use IntStream to create a stream based on the size of your objects like:

IntStream.rangeClosed(1, objects.size()) // both start and end inclusive

and there's also a method IntStream.range(int start, int end) which end is exclusive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM