Package org.awaitility
Class Awaitility
- java.lang.Object
-
- org.awaitility.Awaitility
-
public class Awaitility extends java.lang.ObjectAwaitility is a small Java DSL for synchronizing (waiting for) asynchronous operations. It makes it easy to test asynchronous code. Examples:
Wait at most 5 seconds until customer status has been updated:await().atMost(5, SECONDS).until(customerStatusHasUpdated());
Wait forever until the call toorderService.orderCount()is greater than 3.await().forever().until(() -> orderService.orderCount()), greaterThan(3));
Wait 300 milliseconds until field in objectmyObjectwith namefieldNameand of typeint.classis equal to 4.await().atMost(300, MILLISECONDS).until(fieldIn(orderService).withName("fieldName").andOfType(int.class), equalTo(3));Advanced usage: Use a poll interval of 100 milliseconds with an initial delay of 20 milliseconds until customer status is equal to "REGISTERED". This example also uses a named await by specifying an alias ("customer registration"). This makes it easy to find out which await statement that failed if you have multiple awaits in the same test.with().pollInterval(ONE_HUNDERED_MILLISECONDS).and().with().pollDelay(20, MILLISECONDS).await("customer registration") .until(customerStatus(), equalTo(REGISTERED));You can also specify a default timeout, poll interval and poll delay using:Awaitility.setDefaultTimeout(..) Awaitility.setDefaultPollInterval(..) Awaitility.setDefaultPollDelay(..)
You can also reset to the default values usingreset(). In order to use Awaitility effectively it's recommended to statically import the following methods from the Awaitility framework:- org.awaitility.Awaitlity.*
- org.awaitility.Durations.*
- java.util.concurrent.TimeUnit.*
- org.hamcrest.Matchers.*
- org.junit.Assert.*
A word on poll interval and poll delay: Awaitility starts to check the specified condition (the one you create using the Awaitility DSL) matches for the first time after a "poll delay" (the initial delay before the polling begins). By default Awaitility uses the same poll delay as poll interval which means that it checks the condition periodically first after the given poll delay, and subsequently with the given poll interval; that is conditions are checked after pollDelay then pollDelay+pollInterval, then pollDelay + 2 pollInterval, and so on.
Note: If you change the poll interval the poll delay will also change to match the specified poll interval unless you've specified a poll delay explicitly.
Note that since Awaitility uses polling to verify that a condition matches it's not intended to use it for precise performance testing.
IMPORTANT: Awaitility does nothing to ensure thread safety or thread synchronization! This is your responsibility! Make sure your code is correctly synchronized or that you are using thread safe data structures such as volatile fields or classes such as AtomicInteger and ConcurrentHashMap.
-
-
Field Summary
Fields Modifier and Type Field Description private static java.time.DurationDEFAULT_POLL_DELAYprivate static PollIntervalDEFAULT_POLL_INTERVALprivate static booleandefaultCatchUncaughtExceptionsCatch all uncaught exceptions by default?private static ConditionEvaluationListenerdefaultConditionEvaluationListenerDefault listener of condition evaluation results.private static ExceptionIgnorerdefaultExceptionIgnorerIgnore caught exceptions by default?private static ExecutorLifecycledefaultExecutorLifecycleDefault condition evaluation executor service.private static FailFastConditiondefaultFailFastConditionIf this condition if _ever_ false, indicates our condition will _never_ be true.private static java.time.DurationdefaultPollDelayThe default poll delayprivate static PollIntervaldefaultPollIntervalThe default poll interval (fixed 100 ms).private static WaitConstraintdefaultWaitConstraintThe default wait constraint (10 seconds).
-
Constructor Summary
Constructors Constructor Description Awaitility()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static ConditionFactoryawait()Start building an await statement.static ConditionFactoryawait(java.lang.String alias)Start building a named await statement.static ConditionFactorycatchUncaughtExceptions()Catching uncaught exceptions in other threads.static voidcatchUncaughtExceptionsByDefault()Instruct Awaitility to catch uncaught exceptions from other threads by default.static voiddoNotCatchUncaughtExceptionsByDefault()Instruct Awaitility not to catch uncaught exceptions from other threads.static ConditionFactorydontCatchUncaughtExceptions()Don't catch uncaught exceptions in other threads.static FieldSupplierBuilderfieldIn(java.lang.Class<?> clazz)Await until a static field matches something.static FieldSupplierBuilderfieldIn(java.lang.Object object)Await until an instance field matches something.static ConditionFactorygiven()Start constructing an await statement given some settings.static voidignoreExceptionByDefault(java.lang.Class<? extends java.lang.Throwable> exceptionType)Instruct Awaitility to ignore caught exception of the given type during condition evaluation.static voidignoreExceptionsByDefault()Instruct Awaitility to ignore caught or uncaught exceptions during condition evaluation.static voidignoreExceptionsByDefaultMatching(java.util.function.Predicate<? super java.lang.Throwable> predicate)Instruct Awaitility to ignore caught exceptions matching the givenpredicateduring condition evaluation.static voidignoreExceptionsByDefaultMatching(org.hamcrest.Matcher<? super java.lang.Throwable> matcher)Instruct Awaitility to ignore caught exceptions matching the suppliedmatcherduring condition evaluation.static voidpollExecutorService(java.util.concurrent.ExecutorService executorService)Specify the executor service whose threads will be used to evaluate the poll condition in Awaitility.static voidpollInSameThread()Instructs Awaitility to execute the polling of the condition from the same as the test.static voidpollThread(java.util.function.Function<java.lang.Runnable,java.lang.Thread> threadSupplier)Specify a thread supplier whose thread will be used to evaluate the poll condition in Awaitility.static voidreset()Reset the timeout, poll interval, poll delay, uncaught exception handling to their default values:static voidsetDefaultConditionEvaluationListener(ConditionEvaluationListener defaultConditionEvaluationListener)Sets the default condition evaluation listener that all await statements will use.static voidsetDefaultFailFastCondition(java.lang.String failFastFailureReason, java.util.concurrent.Callable<java.lang.Boolean> defaultFailFastCondition)If the supplied Callable ever returns false, it indicates our condition will never be true, and if so fail the system immediately.static voidsetDefaultFailFastCondition(java.lang.String failFastFailureReason, ThrowingRunnable defaultFailFastAssertion)If the suppliedfailFastAssertionever returns throws an exception, it indicates our condition will never be true, and if so fail the system immediately.static voidsetDefaultFailFastCondition(java.util.concurrent.Callable<java.lang.Boolean> defaultFailFastCondition)If the supplied Callable ever returns false, it indicates our condition will never be true, and if so fail the system immediately.static voidsetDefaultFailFastCondition(ThrowingRunnable defaultFailFastAssertion)If the suppliedfailFastAssertionever returns throws an exception, it indicates our condition will never be true, and if so fail the system immediately.static voidsetDefaultLogging()Sets the default logging condition evaluation listener that all await statements will use.static voidsetDefaultPollDelay(long pollDelay, java.util.concurrent.TimeUnit unit)Sets the default poll delay all await statements will use.static voidsetDefaultPollDelay(java.time.Duration pollDelay)Sets the default poll delay that all await statements will use.static voidsetDefaultPollInterval(long pollInterval, java.util.concurrent.TimeUnit unit)Sets the default poll interval that all await statements will use.static voidsetDefaultPollInterval(java.time.Duration pollInterval)Sets the default poll interval that all await statements will use.static voidsetDefaultPollInterval(PollInterval pollInterval)Sets the default poll interval that all await statements will use.static voidsetDefaultTimeout(long timeout, java.util.concurrent.TimeUnit unit)Sets the default timeout all await statements will use.static voidsetDefaultTimeout(java.time.Duration defaultTimeout)Sets the default timeout that all await statements will use.static voidsetLogging(java.util.function.Consumer<java.lang.String> logPrinter)Sets the default logging condition evaluation listener that all await statements will use.static voidsetLoggingListener(ConditionEvaluationListener loggingListener)Sets the default logging condition evaluation listener that all await statements will use.static ConditionFactorywaitAtMost(long value, java.util.concurrent.TimeUnit unit)An alternative to usingawait()if you want to specify a timeout directly.static ConditionFactorywaitAtMost(java.time.Duration timeout)An alternative to usingawait()if you want to specify a timeout directly.static ConditionFactorywith()Start constructing an await statement with some settings.
-
-
-
Field Detail
-
DEFAULT_POLL_DELAY
private static final java.time.Duration DEFAULT_POLL_DELAY
-
DEFAULT_POLL_INTERVAL
private static final PollInterval DEFAULT_POLL_INTERVAL
-
defaultPollInterval
private static volatile PollInterval defaultPollInterval
The default poll interval (fixed 100 ms).
-
defaultWaitConstraint
private static volatile WaitConstraint defaultWaitConstraint
The default wait constraint (10 seconds).
-
defaultPollDelay
private static volatile java.time.Duration defaultPollDelay
The default poll delay
-
defaultCatchUncaughtExceptions
private static volatile boolean defaultCatchUncaughtExceptions
Catch all uncaught exceptions by default?
-
defaultExceptionIgnorer
private static volatile ExceptionIgnorer defaultExceptionIgnorer
Ignore caught exceptions by default?
-
defaultConditionEvaluationListener
private static volatile ConditionEvaluationListener defaultConditionEvaluationListener
Default listener of condition evaluation results.
-
defaultExecutorLifecycle
private static volatile ExecutorLifecycle defaultExecutorLifecycle
Default condition evaluation executor service.
-
defaultFailFastCondition
private static volatile FailFastCondition defaultFailFastCondition
If this condition if _ever_ false, indicates our condition will _never_ be true.
-
-
Method Detail
-
catchUncaughtExceptionsByDefault
public static void catchUncaughtExceptionsByDefault()
Instruct Awaitility to catch uncaught exceptions from other threads by default. This is useful in multi-threaded systems when you want your test to fail regardless of which thread throwing the exception. Default istrue.
-
doNotCatchUncaughtExceptionsByDefault
public static void doNotCatchUncaughtExceptionsByDefault()
Instruct Awaitility not to catch uncaught exceptions from other threads. Your test will not fail if another thread throws an exception.
-
ignoreExceptionsByDefault
public static void ignoreExceptionsByDefault()
Instruct Awaitility to ignore caught or uncaught exceptions during condition evaluation. Exceptions will be treated as evaluating tofalse. Your test will not fail upon an exception, unless it times out.
-
ignoreExceptionByDefault
public static void ignoreExceptionByDefault(java.lang.Class<? extends java.lang.Throwable> exceptionType)
Instruct Awaitility to ignore caught exception of the given type during condition evaluation. Exceptions will be treated as evaluating tofalse. Your test will not fail upon an exception matching the supplied exception type, unless it times out.
-
ignoreExceptionsByDefaultMatching
public static void ignoreExceptionsByDefaultMatching(java.util.function.Predicate<? super java.lang.Throwable> predicate)
Instruct Awaitility to ignore caught exceptions matching the givenpredicateduring condition evaluation. Exceptions will be treated as evaluating tofalse. Your test will not fail upon an exception matching the supplied predicate, unless it times out.
-
ignoreExceptionsByDefaultMatching
public static void ignoreExceptionsByDefaultMatching(org.hamcrest.Matcher<? super java.lang.Throwable> matcher)
Instruct Awaitility to ignore caught exceptions matching the suppliedmatcherduring condition evaluation. Exceptions will be treated as evaluating tofalse. Your test will not fail upon an exception matching the supplied exception type, unless it times out.
-
pollInSameThread
public static void pollInSameThread()
Instructs Awaitility to execute the polling of the condition from the same as the test. This is an advanced feature and you should be careful when combining this with conditions that wait forever (or a long time) since Awaitility cannot interrupt the thread when using the same thread as the test. For safety you should always combine tests using this feature with a test framework specific timeout, for example in JUnit:- Since:
- 3.0.0
-
pollExecutorService
public static void pollExecutorService(java.util.concurrent.ExecutorService executorService)
Specify the executor service whose threads will be used to evaluate the poll condition in Awaitility. Note that the executor service must be shutdown manually! This is an advanced feature and it should only be used sparingly.- Parameters:
executorService- The executor service that Awaitility will use when polling condition evaluations- Since:
- 3.0.0
-
pollThread
public static void pollThread(java.util.function.Function<java.lang.Runnable,java.lang.Thread> threadSupplier)
Specify a thread supplier whose thread will be used to evaluate the poll condition in Awaitility. The supplier will be called only once and the thread it returns will be reused during all condition evaluations. This is an advanced feature and it should only be used sparingly.- Parameters:
threadSupplier- A supplier of the thread that Awaitility will use when polling- Since:
- 3.0.0
-
reset
public static void reset()
Reset the timeout, poll interval, poll delay, uncaught exception handling to their default values:- timeout - 10 seconds
- poll interval - 100 milliseconds
- poll delay - 100 milliseconds
- Catch all uncaught exceptions - true
- Do not ignore caught exceptions
- Don't handle condition evaluation results
- Don't log anything
- No fail fast condition
-
await
public static ConditionFactory await()
Start building an await statement.- Returns:
- the condition factory
-
await
public static ConditionFactory await(java.lang.String alias)
Start building a named await statement. This is useful is cases when you have several awaits in your test and you need to tell them apart. If a named await timeout's thealiaswill be displayed indicating which await statement that failed.- Parameters:
alias- the alias that will be shown if the await timeouts.- Returns:
- the condition factory
-
catchUncaughtExceptions
public static ConditionFactory catchUncaughtExceptions()
Catching uncaught exceptions in other threads. This will make the await statement fail even if exceptions occur in other threads. This is the default behavior.- Returns:
- the condition factory
-
dontCatchUncaughtExceptions
public static ConditionFactory dontCatchUncaughtExceptions()
Don't catch uncaught exceptions in other threads. This will not make the await statement fail if exceptions occur in other threads.- Returns:
- the condition factory
-
with
public static ConditionFactory with()
Start constructing an await statement with some settings. E.g.with().pollInterval(20, MILLISECONDS).await().until(somethingHappens());
- Returns:
- the condition factory
-
given
public static ConditionFactory given()
Start constructing an await statement given some settings. E.g.given().pollInterval(20, MILLISECONDS).then().await().until(somethingHappens());
- Returns:
- the condition factory
-
waitAtMost
public static ConditionFactory waitAtMost(java.time.Duration timeout)
An alternative to usingawait()if you want to specify a timeout directly.- Parameters:
timeout- the timeout- Returns:
- the condition factory
-
waitAtMost
public static ConditionFactory waitAtMost(long value, java.util.concurrent.TimeUnit unit)
An alternative to usingawait()if you want to specify a timeout directly.- Parameters:
value- the valueunit- the unit- Returns:
- the condition factory
-
setDefaultPollInterval
public static void setDefaultPollInterval(long pollInterval, java.util.concurrent.TimeUnit unit)Sets the default poll interval that all await statements will use.- Parameters:
pollInterval- the poll intervalunit- the unit
-
setDefaultPollDelay
public static void setDefaultPollDelay(long pollDelay, java.util.concurrent.TimeUnit unit)Sets the default poll delay all await statements will use.- Parameters:
pollDelay- the poll delayunit- the unit
-
setDefaultTimeout
public static void setDefaultTimeout(long timeout, java.util.concurrent.TimeUnit unit)Sets the default timeout all await statements will use.- Parameters:
timeout- the timeoutunit- the unit
-
setDefaultPollInterval
public static void setDefaultPollInterval(java.time.Duration pollInterval)
Sets the default poll interval that all await statements will use.- Parameters:
pollInterval- the new default poll interval
-
setDefaultPollInterval
public static void setDefaultPollInterval(PollInterval pollInterval)
Sets the default poll interval that all await statements will use.- Parameters:
pollInterval- the new default poll interval
-
setDefaultPollDelay
public static void setDefaultPollDelay(java.time.Duration pollDelay)
Sets the default poll delay that all await statements will use.- Parameters:
pollDelay- the new default poll delay
-
setDefaultTimeout
public static void setDefaultTimeout(java.time.Duration defaultTimeout)
Sets the default timeout that all await statements will use.- Parameters:
defaultTimeout- the new default timeout
-
setDefaultConditionEvaluationListener
public static void setDefaultConditionEvaluationListener(ConditionEvaluationListener defaultConditionEvaluationListener)
Sets the default condition evaluation listener that all await statements will use.- Parameters:
defaultConditionEvaluationListener- handles condition evaluation each time evaluation of a condition occurs. Works only with Hamcrest matcher-based conditions.
-
setLoggingListener
public static void setLoggingListener(ConditionEvaluationListener loggingListener)
Sets the default logging condition evaluation listener that all await statements will use. Method could override result of usagesetDefaultConditionEvaluationListener(ConditionEvaluationListener).- Parameters:
loggingListener- logging condition evaluation each time evaluation of a condition occurs.- See Also:
setDefaultConditionEvaluationListener(ConditionEvaluationListener)
-
setLogging
public static void setLogging(java.util.function.Consumer<java.lang.String> logPrinter)
Sets the default logging condition evaluation listener that all await statements will use. Method could override result of usagesetDefaultConditionEvaluationListener(ConditionEvaluationListener)with custom consumer.- Parameters:
logPrinter- consumer for condition logging- See Also:
setDefaultConditionEvaluationListener(ConditionEvaluationListener)
-
setDefaultLogging
public static void setDefaultLogging()
Sets the default logging condition evaluation listener that all await statements will use. Method could override result of usagesetDefaultConditionEvaluationListener(ConditionEvaluationListener)with logging to System.out.
-
setDefaultFailFastCondition
public static void setDefaultFailFastCondition(java.util.concurrent.Callable<java.lang.Boolean> defaultFailFastCondition)
If the supplied Callable ever returns false, it indicates our condition will never be true, and if so fail the system immediately. Throws aTerminalFailureExceptionif fail fast condition evaluates totrue. If you want to specify a more descriptive error message then usesetDefaultFailFastCondition(String, Callable).- Parameters:
defaultFailFastCondition- The terminal failure condition- See Also:
setDefaultFailFastCondition(String, Callable)
-
setDefaultFailFastCondition
public static void setDefaultFailFastCondition(ThrowingRunnable defaultFailFastAssertion)
If the suppliedfailFastAssertionever returns throws an exception, it indicates our condition will never be true, and if so fail the system immediately. This allows you to use a more descriptive error message of why the fail-fast condition failed instead of usingsetDefaultFailFastCondition(String, Callable).- Parameters:
defaultFailFastAssertion- The terminal failure assertion- See Also:
setDefaultFailFastCondition(Callable),ConditionFactory.failFast(ThrowingRunnable)
-
setDefaultFailFastCondition
public static void setDefaultFailFastCondition(java.lang.String failFastFailureReason, ThrowingRunnable defaultFailFastAssertion)If the suppliedfailFastAssertionever returns throws an exception, it indicates our condition will never be true, and if so fail the system immediately. This allows you to use a more descriptive error message of why the fail-fast condition failed instead of usingsetDefaultFailFastCondition(String, Callable).- Parameters:
failFastFailureReason- A descriptive reason why the fail fast condition has failed, will be included in theTerminalFailureExceptionthrown iffailFastAssertionthrows an exception.defaultFailFastAssertion- The terminal failure assertion- See Also:
setDefaultFailFastCondition(Callable),ConditionFactory.failFast(ThrowingRunnable)
-
setDefaultFailFastCondition
public static void setDefaultFailFastCondition(java.lang.String failFastFailureReason, java.util.concurrent.Callable<java.lang.Boolean> defaultFailFastCondition)If the supplied Callable ever returns false, it indicates our condition will never be true, and if so fail the system immediately. Throws aTerminalFailureExceptionif fail fast condition evaluates totrue.- Parameters:
defaultFailFastCondition- The terminal failure conditionfailFastFailureReason- A descriptive reason why the fail fast condition has failed, will be included in theTerminalFailureExceptionthrown iffailFastConditionevaluates totrue.
-
fieldIn
public static FieldSupplierBuilder fieldIn(java.lang.Object object)
Await until an instance field matches something. E.g.await().until(fieldIn(service).ofType(int.class).andWithName("fieldName"), greaterThan(2));Here Awaitility waits until a field with name
fieldNameand of theint.classin objectserviceis greater than 2.Note that the field must be thread-safe in order to guarantee correct behavior.
- Parameters:
object- The object that contains the field.- Returns:
- A field supplier builder which lets you specify the parameters needed to find the field.
-
fieldIn
public static FieldSupplierBuilder fieldIn(java.lang.Class<?> clazz)
Await until a static field matches something. E.g.await().until(fieldIn(Service.class).ofType(int.class).andWithName("fieldName"), greaterThan(2));Here Awaitility waits until a static field with name
fieldNameand of theint.classin objectserviceis greater than 2.Note that the field must be thread-safe in order to guarantee correct behavior.
- Parameters:
clazz- The class that contains the static field.- Returns:
- A field supplier builder which lets you specify the parameters needed to find the field.
-
-