Java 8流中的JUnit断言 [英] JUnit assertions within in Java 8 stream

查看:109
本文介绍了Java 8流中的JUnit断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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))
    .????

但我不知道我的断言的位置()会进入这样的声明。或者我的方法是错的?我知道我可以使用简单的for循环,但我喜欢流的优雅。另外,有没有办法动态创建intArray,以防我有超过3个myObjects?

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

这篇关于Java 8流中的JUnit断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆