Tabnine Logo
Awaitility
Code IndexAdd Tabnine to your IDE (free)

How to use
Awaitility
in
org.awaitility

Best Java code snippets using org.awaitility.Awaitility (Showing top 20 results out of 990)

Refine searchRefine arrow

  • ConditionFactory
  • Matchers
origin: awaitility/awaitility

@Test(timeout = 2000)
public void typeOnly() throws Exception {
  new Asynch(fakeRepository).perform();
  await().until(fieldIn(fakeRepository).ofType(int.class), equalTo(1));
  assertEquals(1, fakeRepository.getValue());
}
origin: awaitility/awaitility

@Test(timeout = 2000)
public void awaitOperationSupportsSpecifyingPollIntervalUsingTimeunit() {
  new Asynch(fakeRepository).perform();
  with().pollInterval(20, TimeUnit.MILLISECONDS).await().until(fakeRepositoryValueEqualsOne());
  given().pollInterval(20, TimeUnit.MILLISECONDS).await().until(fakeRepositoryValueEqualsOne());
  assertEquals(1, fakeRepository.getValue());
}
origin: awaitility/awaitility

@Test(timeout = 2000, expected = IllegalStateException.class)
public void uncaughtExceptionsArePropagatedToAwaitingThreadAndBreaksForeverBlockWhenSetToCatchAllUncaughtExceptions() {
  catchUncaughtExceptionsByDefault();
  new ExceptionThrowingAsynch(new IllegalStateException("Illegal state!")).perform();
  await().forever().until(value(), equalTo(1));
}
origin: awaitility/awaitility

@Test(timeout = 2000)
public void exceptionIgnoringWorksForHamcrestMatchersStatically() {
  new Asynch(fakeRepository).perform();
  Awaitility.ignoreExceptionsByDefaultMatching(instanceOf(RuntimeException.class));
  await().atMost(1000, MILLISECONDS).until(conditionsThatIsThrowingAnExceptionForATime(IllegalArgumentException.class));
}
origin: awaitility/awaitility

@Test(timeout = 2000L, expected = ConditionTimeoutException.class)
public void awaitOperationSupportsDefaultTimeout() {
  Awaitility.setDefaultTimeout(120, TimeUnit.MILLISECONDS);
  await().until(value(), greaterThan(0));
  assertEquals(1, fakeRepository.getValue());
}
origin: graphql-java/java-dataloader

@Test
public void will_compose_multiple_futures() throws Exception {
  CompletableFuture<Integer> f1 = supplyAsync(() -> 666);
  CompletableFuture<Integer> f2 = supplyAsync(() -> 999);
  PromisedValues<Integer> promisedValues = PromisedValues.allOf(f1, f2);
  assertThat(promisedValues.size(), equalTo(2));
  await().until(promisedValues::isDone, is(true));
  assertThat(promisedValues.toList(), equalTo(asList(666, 999)));
}
origin: graphql-java/java-dataloader

@Test
public void should_Support_loading_multiple_keys_in_one_call() {
  AtomicBoolean success = new AtomicBoolean();
  DataLoader<Integer, Integer> identityLoader = new DataLoader<>(keysAsValues());
  CompletionStage<List<Integer>> futureAll = identityLoader.loadMany(asList(1, 2));
  futureAll.thenAccept(promisedValues -> {
    assertThat(promisedValues.size(), is(2));
    success.set(true);
  });
  identityLoader.dispatch();
  await().untilAtomic(success, is(true));
  assertThat(futureAll.toCompletableFuture().join(), equalTo(asList(1, 2)));
}
origin: awaitility/awaitility

@Test(timeout = 2000, expected = IllegalStateException.class)
public void exceptionsInConditionsArePropagatedToAwaitingThreadAndBreaksForeverBlock() {
  final ExceptionThrowingFakeRepository repository = new ExceptionThrowingFakeRepository();
  new Asynch(repository).perform();
  await().until(new FakeRepositoryValue(repository), equalTo(1));
}
origin: awaitility/awaitility

@Test(timeout = 2000)
public void usingAtomicReferenceAndTimeout() throws Exception {
  exception.expect(ConditionTimeoutException.class);
  exception.expectMessage(
      "org.awaitility.core.ConditionFactory.untilAtomic Callable expected \"1\" but was \"0\" within 200 milliseconds.");
  AtomicReference<String> atomic = new AtomicReference<String>("0");
  await().atMost(200, MILLISECONDS).untilAtomic(atomic, equalTo("1"));
}
origin: graphql-java/java-dataloader

@Test
public void should_Resolve_to_empty_list_when_no_keys_supplied() {
  AtomicBoolean success = new AtomicBoolean();
  DataLoader<Integer, Integer> identityLoader = new DataLoader<>(keysAsValues());
  CompletableFuture<List<Integer>> futureEmpty = identityLoader.loadMany(emptyList());
  futureEmpty.thenAccept(promisedValues -> {
    assertThat(promisedValues.size(), is(0));
    success.set(true);
  });
  identityLoader.dispatch();
  await().untilAtomic(success, is(true));
  assertThat(futureEmpty.join(), empty());
}
origin: awaitility/awaitility

@Test(timeout = 2000)
public void usingAtomicInteger() throws Exception {
  AtomicInteger atomic = new AtomicInteger(0);
  new Asynch(new FakeRepositoryWithAtomicInteger(atomic)).perform();
  await().untilAtomic(atomic, equalTo(1));
}
origin: ben-manes/caffeine

 assertThat(v.key, is(k));
 if (!v.live.compareAndSet(true, false)) {
  throw new RuntimeException(String.format(
await().until(() -> inserts.get() == removals.get());
assertThat(failed.get(), is(false));
origin: awaitility/awaitility

@Test(timeout = 2000)
public void exceptionsDuringEvaluationAreReportedByDefault() {
  exception.expect(RuntimeException.class);
  exception.expectMessage(is("Repository value is not 1"));
  new Asynch(fakeRepository).perform();
  await().atMost(1000, MILLISECONDS).with().until(conditionsThatIsThrowingAnExceptionForATime(RuntimeException.class));
}
origin: spring-projects/spring-framework

@Test
public void getMultipleInstances() throws Exception {
  // Arrange
  TestBean[] beans = new TestBean[2];
  Thread thread1 = new Thread(() -> beans[0] = applicationContext.getBean("threadScopedObject", TestBean.class));
  Thread thread2 = new Thread(() -> beans[1] = applicationContext.getBean("threadScopedObject", TestBean.class));
  // Act
  thread1.start();
  thread2.start();
  // Assert
  Awaitility.await()
        .atMost(500, TimeUnit.MILLISECONDS)
        .pollInterval(10, TimeUnit.MILLISECONDS)
        .until(() -> (beans[0] != null) && (beans[1] != null));
  assertNotSame(beans[0], beans[1]);
}
origin: awaitility/awaitility

@Test(timeout = 3000, expected = ConditionTimeoutException.class)
public void throwsTimeoutExceptionWhenDoneEarlierThanAtLeastConstraint() {
  new Asynch(fakeRepository).perform();
  await().atLeast(1, SECONDS).and().atMost(2, SECONDS).until(value(), equalTo(1));
}
origin: awaitility/awaitility

  @Override
  public void testLogic() {
    new ExceptionThrowingAsynch(new IllegalStateException("Illegal state!")).perform();
    await().and().dontCatchUncaughtExceptions().given().timeout(ONE_SECOND).until(value(), equalTo(1));
  }
};
origin: awaitility/awaitility

@Test(timeout = 3000)
public void doesNotThrowTimeoutExceptionWhenDoneLaterThanAtLeastConstraint() {
  new Asynch(fakeRepository).perform();
  await().atLeast(100, NANOSECONDS).until(value(), equalTo(1));
}
origin: awaitility/awaitility

@Test(timeout = 2000)
public void specifyingDefaultPollIntervalImpactsAllSubsequentUndefinedPollIntervalStatements() {
  Awaitility.setDefaultPollInterval(20, TimeUnit.MILLISECONDS);
  new Asynch(fakeRepository).perform();
  await().until(value(), equalTo(1));
  assertEquals(1, fakeRepository.getValue());
}
origin: awaitility/awaitility

@Test(timeout = 2000)
public void assertionErrorIgnoringWorksForHamcrestMatchers() {
  new Asynch(fakeRepository).perform();
  await().atMost(1000, MILLISECONDS).with().ignoreExceptionsMatching(instanceOf(AssertionError.class)).until(conditionsThatIsThrowingAnExceptionForATime(AssertionError.class));
}
origin: awaitility/awaitility

@Test(timeout = 2000)
public void noIgnoredExceptionsHavePrecedenceOverStaticallyDefinedExceptionIgnorer() {
  exception.expect(IllegalArgumentException.class);
  exception.expectMessage("Repository value is not 1");
  new Asynch(fakeRepository).perform();
  Awaitility.ignoreExceptionsByDefaultMatching(instanceOf(RuntimeException.class));
  await().atMost(1000, MILLISECONDS).with().ignoreNoExceptions().until(conditionsThatIsThrowingAnExceptionForATime(IllegalArgumentException.class));
}
org.awaitilityAwaitility

Javadoc

Awaitility 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 to orderService.orderCount() is greater than 3.

 
await().forever().untilCall(to(orderService).orderCount(), greaterThan(3)); 

Wait 300 milliseconds until field in object myObject with name fieldName and of type int.class is 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 using org.awaitility.Awaitility#reset(). In order to use Awaitility effectively it's recommended to statically import the following methods from the Awaitility framework:

 

  • org.awaitility.Awaitlity.*
It may also be useful to import these methods:
  • org.awaitility.Duration.*
  • 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.

Most used methods

  • await
    Start building a named await statement. This is useful is cases when you have several awaits in your
  • waitAtMost
    An alternative to using #await() if you want to specify a timeout directly.
  • given
    Start constructing an await statement given some settings. E.g. given().pollInterval(20, MILLISECON
  • setDefaultPollInterval
    Sets the default poll interval that all await statements will use.
  • with
    Start constructing an await statement with some settings. E.g. with().pollInterval(20, MILLISECONDS
  • setDefaultTimeout
    Sets the default timeout that all await statements will use.
  • catchUncaughtExceptions
    Catching uncaught exceptions in other threads. This will make the await statement fail even if excep
  • catchUncaughtExceptionsByDefault
    Instruct Awaitility to catch uncaught exceptions from other threads by default. This is useful in mu
  • dontCatchUncaughtExceptions
    Don't catch uncaught exceptions in other threads. This will not make the await statement fail if exc
  • fieldIn
    Await until an instance field matches something. E.g. await().until(fieldIn(service).ofType(int.cla
  • ignoreExceptionsByDefault
    Instruct Awaitility to ignore caught or uncaught exceptions during condition evaluation. Exceptions
  • ignoreExceptionsByDefaultMatching
    Instruct Awaitility to ignore caught exceptions matching the supplied matcher during condition eval
  • ignoreExceptionsByDefault,
  • ignoreExceptionsByDefaultMatching,
  • reset,
  • setDefaultConditionEvaluationListener

Popular in Java

  • Parsing JSON documents to java classes using gson
  • requestLocationUpdates (LocationManager)
  • onRequestPermissionsResult (Fragment)
  • getSystemService (Context)
  • BufferedImage (java.awt.image)
    The BufferedImage subclass describes an java.awt.Image with an accessible buffer of image data. All
  • InetAddress (java.net)
    An Internet Protocol (IP) address. This can be either an IPv4 address or an IPv6 address, and in pra
  • URLEncoder (java.net)
    This class is used to encode a string using the format required by application/x-www-form-urlencoded
  • Permission (java.security)
    Legacy security code; do not use.
  • LinkedHashMap (java.util)
    LinkedHashMap is an implementation of Map that guarantees iteration order. All optional operations a
  • Servlet (javax.servlet)
    Defines methods that all servlets must implement. A servlet is a small Java program that runs within
  • Top plugins for WebStorm
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimAtomGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyStudentsTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now