diff --git a/documentation/src/docs/asciidoc/user-guide/writing-tests.adoc b/documentation/src/docs/asciidoc/user-guide/writing-tests.adoc index abe9402f4340..d43113b851ae 100644 --- a/documentation/src/docs/asciidoc/user-guide/writing-tests.adoc +++ b/documentation/src/docs/asciidoc/user-guide/writing-tests.adoc @@ -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 diff --git a/documentation/src/test/java/example/PollingTimeout.java b/documentation/src/test/java/example/PollingTimeout.java new file mode 100644 index 000000000000..a27ac7a0c314 --- /dev/null +++ b/documentation/src/test/java/example/PollingTimeout.java @@ -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; + } +}