[英]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. 假设我有三个对象保存到数据库并将db生成的ID设置为。 I don't know the order of the objects returned from the method
saveToDb
. 我不知道从方法
saveToDb
返回的对象的顺序。 But I want to junit test that those generated IDs are there. 但是我想对这些生成的ID进行测试。 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. 但是我不确定我的
assertEquals()
会在这样的语句中出现在哪里。 Or is my approach all wrong? 或者我的方法都错了? I know I could use a simple for-loop, but I like the elegance of streams.
我知道我可以使用简单的for循环,但我喜欢流的优雅。 Additionally, is there a way to dynamically create the intArray, in case I have more than 3 myObjects?
另外,有没有办法动态创建intArray,以防我有超过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? 所以你基本上想检查一个MyObject实例是否被分配了一个ID? Is the equalness to the IDs in the array from any importance?
与任何重要性的数组中的ID是否相等?
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. 假设MyObject上有一个“getId”方法。
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?
另外,有没有办法动态创建intArray,以防我有超过3个myObjects?
Yes you can use IntStream
to create a stream based on the size of your objects like: 是的,您可以使用
IntStream
根据对象的大小创建流,如:
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. 并且还有一个方法
IntStream.range(int start, int end)
,其end
是独占的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.