Created
September 22, 2017 08:02
-
-
Save moelholm/91729e6dc382f9556d46769922f43693 to your computer and use it in GitHub Desktop.
assertEventualCollectionCondition ... awaiting some future condition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// >>> 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