Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions documentation/src/docs/asciidoc/user-guide/writing-tests.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -1659,6 +1659,25 @@ omitted. Specifying no unit is equivalent to using seconds.
| `42 d` | `@Timeout(value = 42, unit = DAYS)`
|===

==== Use @Timeout for polling tests

It is common to write tests waiting for some updates.
In some cases you can rewrite the logic to use a `CountDownLatch` or any other synchronization
mechanism but sometimes it is not possible - generally when depending on an external system.
These tests require some timeout to ensure they don't hang the test suite forever and
the test fails if the waiting condition "never" happens.
With `@Timeout` it becomes very easy to write such tests since the test itself just require
to become an infinite loop:

[source,java]
----
include::{testDir}/example/PollingTimeout.java[tags=user_guide,indent=0]
----

Such a simple usage enables to implement "test when" or "wait until" logic very easily.

Alternatively, you can use a library handling for you the awaiting like the well-known
link:https://github.com/awaitility/awaitility[Awaitility].

[[writing-tests-parallel-execution]]
=== Parallel Execution
Expand Down
29 changes: 29 additions & 0 deletions documentation/src/test/java/example/PollingTimeout.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright 2015-2019 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v2.0 which
* accompanies this distribution and is available at
*
* https://www.eclipse.org/legal/epl-v20.html
*/

package example;

import org.junit.jupiter.api.Timeout;

class PollingTimeout {
// tag::user_guide[]
@Timeout(5) // 5s
void waitUntil() throws InterruptedException {
while (!isConditionTrue()) {
Thread.sleep(250); // use some adapted retry duration
}
// if needed asserts on the result of the awaited condition
}
// end::user_guide[]

private boolean isConditionTrue() {
return true;
}
}