Kotlin

Kotlin

Asserting asynchronous task #

Sometimes CountdownLatch is not feasible as it is not possible to inject it. The alternative pool until the system reaches the desired state. This approach is not ideal as it may block the system longer than strictly required.

As mid-term solution, in any-case opt for CountdownLatch if possible.

fun assertWaitFor(timeoutMs: Long = 5000, intervalMs: Long = 250, fn: () -> Unit) {
    val start = Instant.now()
    var lastError: Throwable? = null
    while (Duration.between(start, Instant.now()).toMillis() <= timeoutMs) {
	try {
	    fn()
	    return
	} catch (ex: AssertionError) {
	    lastError = ex
	}
	Thread.sleep(intervalMs)
    }

    fail("Failed to reach expected condition within $timeoutMs ms.", lastError!!)
}