Java 8 流中的 JUnit 断言

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43092438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:04:29  来源:igfitidea点击:

JUnit assertions within in Java 8 stream

javajunitjava-stream

提问by user1660256

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:

假设我将三个对象保存到数据库中并将数据库生成的 ID 设置到其中。我不知道从方法返回的对象的顺序saveToDb。但我想 junit 测试那些生成的 ID 是否在那里。我如何在流中做到这一点?我想做这样的事情:

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?

但我不确定在assertEquals()这样的声明中我会去哪里。还是我的方法全错了?我知道我可以使用简单的 for 循环,但我喜欢流的优雅。另外,如果我有 3 个以上的 myObjects,有没有办法动态创建 intArray?

采纳答案by Eugene

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

回答by shizhz

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?

另外,如果我有 3 个以上的 myObjects,有没有办法动态创建 intArray?

Yes you can use IntStreamto 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 endis exclusive.

也有一个方法,IntStream.range(int start, int end)end是唯一的。

回答by skombijohn

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?

所以你基本上想检查一个 MyObject 实例是否被分配了一个 ID?与数组中的 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”方法。