Skip to content

Instantly share code, notes, and snippets.

@moelholm
Created September 22, 2017 08:02
Show Gist options
  • Save moelholm/91729e6dc382f9556d46769922f43693 to your computer and use it in GitHub Desktop.
Save moelholm/91729e6dc382f9556d46769922f43693 to your computer and use it in GitHub Desktop.
assertEventualCollectionCondition ... awaiting some future condition
// >>> How to use
assertEventualCollectionCondition(
() -> em.createQuery("from Dog").getResultList(),
Collection::isEmpty);
// >>>
private <T> void assertEventualCollectionCondition(Supplier<Collection<T>> supplier, Predicate<Collection<T>> test) throws Exception {
assertEventualCollectionCondition(30, TimeUnit.SECONDS, supplier, test);
}
private <T> void assertEventualCollectionCondition(int timeOut, TimeUnit timeUnit, Supplier<Collection<T>> supplier, Predicate<Collection<T>> test) throws Exception {
final long stopTimeMillis = System.currentTimeMillis() + timeUnit.toMillis(timeOut);
while (true) {
Collection<T> elements = supplier.get();
if (test.test(elements)) {
return;
}
if (System.currentTimeMillis() > stopTimeMillis) {
fail(String.format("Timed out waiting for collection condition. Resulting collection had [%s] elements. Contents: %s", (elements == null) ? null : elements.size(), elements));
} else {
TimeUnit.SECONDS.sleep(1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment