【问题标题】:Return collection from await从等待返回集合
【发布时间】:2019-06-28 06:32:56
【问题描述】:

我正在使用 Awaitility 工具,我需要从 await 返回一个集合,以便以后能够使用它。

我有一个从 GET 调用返回的集合:

Collection collection = usersService.getAllUsers();

以下代码有效(GET调用最多执行5次以满足条件):

    waitForEvent(() -> usersService.getAllUsers()).size());

地点:

private void waitForEvent(Callable<Integer> collectionSize) {
    await().atMost(5, TimeUnit.SECONDS)
            .pollDelay(1, TimeUnit.SECONDS).until(collectionSize, greaterThan(5));
}

但我需要传递一个集合(而不是它的大小)才能重用它。为什么这段代码不起作用(GET 调用只执行一次并等待 5 秒)?

waitForEvent2(usersService.getAllUsers());

在哪里

private Collection waitForEvent2(Collection collection) {
    await().atMost(5, TimeUnit.SECONDS)
            .pollDelay(1, TimeUnit.SECONDS).until(collectionSize(collection), greaterThan(5));
    return collection;
}

private Callable<Integer> collectionSize(Collection collection) {
    return new Callable<Integer>() {
        public Integer call() throws Exception {
            return collection.size(); // The condition supplier part
        }
    };
}

我需要做什么才能使 GET 请求被轮询多次,并将集合作为参数传递?

【问题讨论】:

  • 为什么需要返回Collection?对我来说听起来像XY-Problem
  • 我不明白为什么第一个 sn-p 会起作用而第二个不会。问题是第一个 sn-p 不包括 collectionSize 实际上是什么。它是同一个可调用对象吗?
  • 添加了使用示例。 @Lino 我使用 Collection 以便在列表和地图中重用它
  • @Nataliya 是什么阻止你声明Collection 变量并将userService.getAllUsers() 的结果存储在其中?
  • @Lino 我想这是主要问题,因为集合被分配给变量,所以轮询不起作用(GET 请求只执行一次)。似乎轮询适用于size() 方法,而不是usersService.getAllUsers().size()。也就是说usersService.getAllUsers()在重试中不会执行

标签: java awaitility


【解决方案1】:

很明显,在您使用的第一个 sn-p 中

usersService.getAllUsers().size()

这会被多次调用(调用服务 -> 获取调用)

第二次你只使用

collection.size()

这不会获取任何东西 - 因为为什么会 - 但仍然会被调用相同的时间。

你能做的(我不喜欢的)是

private Callable<Integer> collectionSize(Collection collection) {

    return new Callable<Integer>() {
        public Integer call() throws Exception {
            collection.clear();
            collection.addAll(usersService.getAllUsers());
            return collection.size(); // The condition supplier part
        }
    };
}

【讨论】:

  • 谢谢,这个 sn-p 有效。但是有没有可能不对usersService.getAllUsers()进行硬编码,以便我能够重用这个方法?此外,这并不能解决主要问题:GET 请求执行了两次
  • 也许它在 2 次调用后得到正确的大小。您也可以作为生产者传递服务调用。
  • 作为生产者传递服务调用是什么意思?
猜你喜欢
  • 1970-01-01
  • 2013-02-18
  • 2014-06-30
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 2014-10-06
  • 2021-04-30
  • 2013-05-13
相关资源
最近更新 更多