JUnit assertions within in Java 8 stream

2019-06-22 16:26发布

问题:

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?

回答1:

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);


回答2:

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.



回答3:

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.