Skip to content

Commit e6006fe

Browse files
rmannibucausbrannen
authored andcommitted
Add a @timeout example for 'poll until' logic
Closes #1926
1 parent 4d3b0a5 commit e6006fe

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

Diff for: documentation/src/docs/asciidoc/user-guide/writing-tests.adoc

+19
Original file line numberDiff line numberDiff line change
@@ -1695,6 +1695,25 @@ omitted. Specifying no unit is equivalent to using seconds.
16951695
| `42 d` | `@Timeout(value = 42, unit = DAYS)`
16961696
|===
16971697

1698+
==== Use @Timeout for polling tests
1699+
1700+
It is common to write tests waiting for some updates.
1701+
In some cases you can rewrite the logic to use a `CountDownLatch` or any other synchronization
1702+
mechanism but sometimes it is not possible - generally when depending on an external system.
1703+
These tests require some timeout to ensure they don't hang the test suite forever and
1704+
the test fails if the waiting condition "never" happens.
1705+
With `@Timeout` it becomes very easy to write such tests since the test itself just require
1706+
to become an infinite loop:
1707+
1708+
[source,java]
1709+
----
1710+
include::{testDir}/example/PollingTimeout.java[tags=user_guide,indent=0]
1711+
----
1712+
1713+
Such a simple usage enables to implement "test when" or "wait until" logic very easily.
1714+
1715+
Alternatively, you can use a library handling for you the awaiting like the well-known
1716+
link:https://github.com/awaitility/awaitility[Awaitility].
16981717

16991718
[[writing-tests-parallel-execution]]
17001719
=== Parallel Execution
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
* Copyright 2015-2019 the original author or authors.
3+
*
4+
* All rights reserved. This program and the accompanying materials are
5+
* made available under the terms of the Eclipse Public License v2.0 which
6+
* accompanies this distribution and is available at
7+
*
8+
* https://www.eclipse.org/legal/epl-v20.html
9+
*/
10+
11+
package example;
12+
13+
import org.junit.jupiter.api.Timeout;
14+
15+
class PollingTimeout {
16+
// tag::user_guide[]
17+
@Timeout(5) // 5s
18+
void waitUntil() throws InterruptedException {
19+
while (!isConditionTrue()) {
20+
Thread.sleep(250); // use some adapted retry duration
21+
}
22+
// if needed asserts on the result of the awaited condition
23+
}
24+
// end::user_guide[]
25+
26+
private boolean isConditionTrue() {
27+
return true;
28+
}
29+
}

0 commit comments

Comments
 (0)