Source:Testing with Thread.sleep
if ( foo.equals("bar") ) {
 // ...
}
Best Selenium code snippet using org.openqa.selenium.support.ui.Interface Sleeper
Source:MyFluentWait.java  
1package com.saucelabs.example;2// Licensed to the Software Freedom Conservancy (SFC) under one3// or more contributor license agreements.  See the NOTICE file4// distributed with this work for additional information5// regarding copyright ownership.  The SFC licenses this file6// to you under the Apache License, Version 2.0 (the7// "License"); you may not use this file except in compliance8// with the License.  You may obtain a copy of the License at9//10//   http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing,13// software distributed under the License is distributed on an14// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY15// KIND, either express or implied.  See the License for the16// specific language governing permissions and limitations17// under the License.18import com.google.common.base.Throwables;19import com.google.common.collect.ImmutableList;20import com.google.common.collect.Lists;21import org.openqa.selenium.TimeoutException;22import org.openqa.selenium.WebDriverException;23import org.openqa.selenium.support.ui.Sleeper;24import org.openqa.selenium.support.ui.Wait;25import java.time.temporal.ChronoUnit;26import java.time.temporal.TemporalUnit;27import java.util.Collection;28import java.util.List;29import java.util.concurrent.TimeUnit;30import java.util.function.Function;31import java.util.function.Supplier;32import static com.google.common.base.Preconditions.checkNotNull;33//import static java.util.concurrent.TimeUnit.MILLISECONDS;34//import static java.util.concurrent.TimeUnit.SECONDS;35import java.time.Clock;36import java.time.Duration;37//import org.openqa.selenium.support.ui.Clock;38//import org.openqa.selenium.support.ui.Duration;39//import org.openqa.selenium.support.ui.Sleeper;40//import org.openqa.selenium.support.ui.SystemClock;41//import org.openqa.selenium.support.ui.Wait;42/**43 * An implementation of the {@link Wait} interface that may have its timeout and polling interval44 * configured on the fly.45 * <p>46 * <p>47 * Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as48 * the frequency with which to check the condition. Furthermore, the user may configure the wait to49 * ignore specific types of exceptions whilst waiting, such as50 * {@link org.openqa.selenium.NoSuchElementException NoSuchElementExceptions} when searching for an51 * element on the page.52 * <p>53 * <p>54 * Sample usage: <pre>55 *   // Waiting 30 seconds for an element to be present on the page, checking56 *   // for its presence once every 5 seconds.57 *   Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)58 *       .withTimeout(30, SECONDS)59 *       .pollingEvery(5, SECONDS)60 *       .ignoring(NoSuchElementException.class);61 * <p>62 *   WebElement foo = wait.until(new Function<WebDriver, WebElement>() {63 *     public WebElement apply(WebDriver driver) {64 *       return driver.findElement(By.id("foo"));65 *     }66 *   });67 * </pre>68 * <p>69 * <p>70 * <em>This class makes no thread safety guarantees.</em>71 *72 * @param <T> The input type for each condition used with this instance.73 */74public class MyFluentWait<T> implements Wait<T>75{76    public static final Duration FIVE_HUNDRED_MILLIS = Duration.of(500, ChronoUnit.MILLIS);77    private final T input;78    private final Clock clock;79    private final Sleeper sleeper;80    private Duration timeout = FIVE_HUNDRED_MILLIS;81    private Duration interval = FIVE_HUNDRED_MILLIS;82    private Supplier<String> messageSupplier = () -> null;83    private List<Class<? extends Throwable>> ignoredExceptions = Lists.newLinkedList();84    /**85     * @param input The input value to pass to the evaluated conditions.86     */87    public MyFluentWait(T input)88    {89        this(input, Clock.systemDefaultZone(), Sleeper.SYSTEM_SLEEPER);90    }91    /**92     * @param input   The input value to pass to the evaluated conditions.93     * @param clock   The clock to use when measuring the timeout.94     * @param sleeper Used to put the thread to sleep between evaluation loops.95     */96    public MyFluentWait(T input, Clock clock, Sleeper sleeper)97    {98        this.input = checkNotNull(input);99        this.clock = checkNotNull(clock);100        this.sleeper = checkNotNull(sleeper);101    }102    /**103     * Sets how long to wait for the evaluated condition to be true. The default timeout is104     * {@link #FIVE_HUNDRED_MILLIS}.105     *106     * @param duration The timeout duration.107     * @param unit     The unit of time.108     * @return A self reference.109     */110    public MyFluentWait<T> withTimeout(long duration, TemporalUnit unit)111    {112        this.timeout = Duration.of(duration, unit);113        return this;114    }115    /**116     * Sets the message to be displayed when time expires.117     *118     * @param message to be appended to default.119     * @return A self reference.120     */121    public MyFluentWait<T> withMessage(final String message)122    {123        this.messageSupplier = () -> message;124        return this;125    }126    /**127     * Sets the message to be evaluated and displayed when time expires.128     *129     * @param messageSupplier to be evaluated on failure and appended to default.130     * @return A self reference.131     */132    public MyFluentWait<T> withMessage(Supplier<String> messageSupplier)133    {134        this.messageSupplier = messageSupplier;135        return this;136    }137    /**138     * Sets how often the condition should be evaluated.139     * <p>140     * <p>141     * In reality, the interval may be greater as the cost of actually evaluating a condition function142     * is not factored in. The default polling interval is {@link #FIVE_HUNDRED_MILLIS}.143     *144     * @param duration The timeout duration.145     * @param unit     The unit of time.146     * @return A self reference.147     */148    public MyFluentWait<T> pollingEvery(long duration, TemporalUnit unit)149    {150        this.interval = Duration.of(duration, unit);151        return this;152    }153    /**154     * Configures this instance to ignore specific types of exceptions while waiting for a condition.155     * Any exceptions not whitelisted will be allowed to propagate, terminating the wait.156     *157     * @param types The types of exceptions to ignore.158     * @param <K>   an Exception that extends Throwable159     * @return A self reference.160     */161    public <K extends Throwable> MyFluentWait<T> ignoreAll(Collection<Class<? extends K>> types)162    {163        ignoredExceptions.addAll(types);164        return this;165    }166    /**167     * @param exceptionType exception to ignore168     * @return a self reference169     * @see #ignoreAll(Collection)170     */171    public MyFluentWait<T> ignoring(Class<? extends Throwable> exceptionType)172    {173        return this.ignoreAll(ImmutableList.<Class<? extends Throwable>>of(exceptionType));174    }175    /**176     * @param firstType  exception to ignore177     * @param secondType another exception to ignore178     * @return a self reference179     * @see #ignoreAll(Collection)180     */181    public MyFluentWait<T> ignoring(Class<? extends Throwable> firstType, Class<? extends Throwable> secondType)182    {183        return this.ignoreAll(ImmutableList.of(firstType, secondType));184    }185    /**186     * Repeatedly applies this instance's input value to the given function until one of the following187     * occurs:188     * <ol>189     * <li>the function returns neither null nor false</li>190     * <li>the function throws an unignored exception</li>191     * <li>the timeout expires</li>192     * <li>the current thread is interrupted</li>193     * </ol>194     *195     * @param isTrue the parameter to pass to the {@link ExpectedCondition}196     * @param <V>    The function's expected return type.197     * @return The function's return value if the function returned something different198     * from null or false before the timeout expired.199     * @throws TimeoutException If the timeout expires.200     */201    @Override202    public <V> V until(Function<? super T, V> isTrue)203    {204        long end = Clock.offset(clock, timeout).millis();205//        long end = clock.laterBy(timeout.in(MILLISECONDS));206        Throwable lastException;207        while (true)208        {209//            System.out.printf(">>> MFW trying...\n");210            try211            {212                V value = isTrue.apply(input);213                if (value != null && (Boolean.class != value.getClass() || Boolean.TRUE.equals(value)))214                {215//                    System.out.printf(">>> MFW returning value: %s\n", value.toString());216                    return value;217                }218                // Clear the last exception; if another retry or timeout exception would219                // be caused by a false or null value, the last exception is not the220                // cause of the timeout.221                lastException = null;222            }223            catch (Throwable e)224            {225                lastException = propagateIfNotIgnored(e);226            }227            // Check the timeout after evaluating the function to ensure conditions228            // with a zero timeout can succeed.229//            if (!clock.isNowBefore(end))230            if (!(System.currentTimeMillis() < end))231            {232                String message = messageSupplier != null ? messageSupplier.get() : null;233                String timeoutMessage = String.format("Expected condition failed: %s (tried for %d second(s) with %s interval)",234                        message == null ? "waiting for " + isTrue : message, timeout.getSeconds(), interval);235//                System.out.printf(">>> MFW: %s\n", timeoutMessage);236                throw timeoutException(timeoutMessage, lastException);237            }238            try239            {240//                System.out.printf(">>> MFW sleeping...\n");241                sleeper.sleep(interval);242            }243            catch (InterruptedException e)244            {245                Thread.currentThread().interrupt();246                throw new WebDriverException(e);247            }248        }249    }250    private Throwable propagateIfNotIgnored(Throwable e)251    {252        for (Class<? extends Throwable> ignoredException : ignoredExceptions)253        {254            if (ignoredException.isInstance(e))255            {256                return e;257            }258        }259        Throwables.throwIfUnchecked(e);260        throw new RuntimeException(e);261    }262    /**263     * Throws a timeout exception. This method may be overridden to throw an exception that is264     * idiomatic for a particular test infrastructure, such as an AssertionError in JUnit4.265     *266     * @param message       The timeout message.267     * @param lastException The last exception to be thrown and subsequently suppressed while waiting268     *                      on a function.269     * @return Nothing will ever be returned; this return type is only specified as a convenience.270     */271    protected RuntimeException timeoutException(String message, Throwable lastException)272    {273        throw new TimeoutException(message, lastException);274    }275}...Source:ActionWait.java  
1package nz.govt.msd.utils;2import java.util.Arrays;3import java.util.List;4import java.util.concurrent.TimeUnit;5import org.openqa.selenium.support.ui.Clock;6import org.openqa.selenium.support.ui.Duration;7import org.openqa.selenium.support.ui.Sleeper;8import org.openqa.selenium.support.ui.SystemClock;9import org.slf4j.Logger;10import org.slf4j.LoggerFactory;11import com.google.common.base.Throwables;12import com.google.common.collect.Lists;13/**14 * Similar to Selenium's {@link org.openqa.selenium.support.ui.FluentWait FluentWait} implementation but designed for long running tasks such as querying a15 * database until some data appears.  Unlike {@link org.openqa.selenium.support.ui.FluentWait FluentWait} it handles exceptions other than RuntimeExceptions.16 * Calling the until() method will retry until either true or a non null value is returned.17 *18 * <p>19 * Each ActionWait must defines the maximum amount of time to wait for a condition, as well as20 * the frequency with which to check the condition. Furthermore, the user may configure the wait to21 * ignore specific types of exceptions whilst waiting, warning intervals to log a warning if action is taking 22 * longer than expected, a custom message and the ability to override the default behaviour (throwing a TimeOutException)23 * and just return a value.24 * </p>25 * 26 * <p>27 * Sample usage: <pre>28 * // Waiting 2 minutes for data to appear in database, checking for its presence  29 * // immediately, then after 10 seconds, and every 5 seconds thereafter.30 * ActionWait wait = new ActionWait()31 *        .withTimeout(TimeUnit.MINUTES, 2)32 *        .withPollingIntervals(TimeUnit.SECONDS, 0, 10, 5)33 *        .withForMessage("some data to appear");34 *35 * // Using Java 8 Lambda Expression	36 * String value = wait.until(() -> {37 *     ResultSet rs = stmt.executeQuery(query);38 *	39 *     if (rs.next()) {40 *         return rs.getString("COLUMN");41 *     } else {42 *         return null;43 *     }44 * });45 *46 * // Using new Function - prior to Java 847 * String value = wait.until(new IsTrue{@literal <String>}() {48 *     {@literal @Override}49 *     public String apply() {50 *         ...51 *     }52 * });53 * </pre>54 * </p>55 *56 * <em>This class makes no thread safety guarantees.</em>57 *58 * @author Andrew Sumner59 */60public class ActionWait {61	private static final Logger LOGGER = LoggerFactory.getLogger(ActionWait.class);62	private Duration timeout;63	private	TimeUnit pollingTimeUnit;64	private List<Integer> pollingIntervals = Lists.newArrayList();65	private	TimeUnit warningTimeUnit = TimeUnit.SECONDS;66	private List<Integer> warningIntervals = Lists.newArrayList();67	private List<Class<? extends Throwable>> ignoredExceptions = Lists.newLinkedList();68	private String message = "";69	private boolean returnResult = false;70	private Clock clock;71	private Sleeper sleeper;72	private int attempts;73	private int warnings;74	75	/**76	 * An interface the caller can implement to check that an action is complete.77	 *78	 * @param <V> The function's expected return type.79	 */80	@FunctionalInterface81	public interface IsComplete<V> {82		/**83		 * Method to implement.84		 * @return An object of the defined return type85		 * @throws Exception If implemented method throws an exception86		 */87		public V apply() throws Exception;88	}89	90	/**91	 * Sets how long to wait for the evaluated condition to be true. Required. 92	 *93	 * @param unit The unit of time.94	 * @param duration The timeout duration.95	 * @return A self reference.96	 */97	public ActionWait withTimeout(TimeUnit unit, long duration) {98		this.timeout = new Duration(duration, unit);99		return this;100	}101	/**102	 * Sets the polling intervals.  Required.103	 * 104	 * @param unit The unit of time.105	 * @param intervals List of polling intervals.  To try immediately first value should be zero, if timeout has not expired and106	 * then last interval is used repeatedly until reach timeout value or successful result returned.107	 * @return A self reference.108	 */109	public ActionWait withPollingIntervals(TimeUnit unit, Integer... intervals) {110		this.pollingTimeUnit = unit;111		this.pollingIntervals.addAll(Arrays.asList(intervals));112		return this;113	}114	/**115	 * Sets a list of intervals at which to display a warning message if successful response has not been returned.116	 * @param unit The unit of time.117	 * @param intervals Each interval will be evaluated once the prior interval has passed.  An interval is measured from the 118	 * 						start of the action so ignores whatever intervals have been used before it.  119	 * @return A self reference.120	 */121	public ActionWait withWarningIntervals(TimeUnit unit, Integer... intervals) {122		this.warningTimeUnit = unit;123		this.warningIntervals.addAll(Arrays.asList(intervals));124		return this;125	}126	/**127	 * Adds a list of Exceptions that should be ignored if thrown when evaluating {@link #until(IsComplete)} method.128	 * 129	 * @param exceptionType Exceptions to ignore130	 * @return A self reference.131	 */132	@SafeVarargs133	public final ActionWait ignoring(Class<? extends Throwable>... exceptionType) {134		this.ignoredExceptions.addAll(Arrays.asList(exceptionType));135		return this;136	}137	/**138	 * Sets some text to be append to timeout and warning messages.139	 *140	 * @param message to be appended to default.141	 * @return A self reference.142	 */143	public ActionWait withForMessage(final String message) {144		this.message = message;145		return this;146	}147	148	/**149	 * By default a timeout exception will be thrown, this will override.150	 * 151	 * that behaviour and cause a result to be returned 152	 * 153	 * @return A self reference.154	 */155	public ActionWait withTimeoutReturningResult() {156		this.returnResult = true;157		return this;158	}159	160	/**161	 * @return The number of attempts taken, starting at 1162	 */163	public int getAttempts() {164		return attempts + 1;165	}166	/**167	 * Repeatedly applies this instance's input value to the given function until one of the following168	 * occurs:169	 * <ol>170	 * <li>the function returns either true or a not null value,</li>171	 * <li>the function throws an unignored exception,</li>172	 * <li>the timeout expires,173	 * <li>the current thread is interrupted</li>174	 * </ol>175	 *176	 * @param isTrue the parameter to pass to the {@link IsComplete}177	 * @param <V> The function's expected return type.178	 * @return The functions' return value if the function returned something different179	 *         from null or false before the timeout expired.180	 * @throws TimeoutException If the timeout expires.181	 */182	public <V> V until(IsComplete<V> isTrue) {183		Throwable lastException = null;184		V value = null;185		clock = new SystemClock();186		sleeper = Sleeper.SYSTEM_SLEEPER;187		188		boolean loggedWait = false;189		long start = clock.now();190		long end = clock.laterBy(timeout.in(TimeUnit.MILLISECONDS));191		while (hasMoreTime(clock, end)) {192			int interval = getNextPollingInterval(clock, end);193			if (interval > 0) {194				if (!loggedWait) {195					loggedWait = true;196					LOGGER.debug("Waiting for up to {}{}{}", timeout.toString().toLowerCase(), (hasMessage() ? " for " : ""), message);197				}198				try {199					LOGGER.trace("Pausing for {} {}", interval, pollingTimeUnit.toString().toLowerCase());200					sleeper.sleep(new Duration(interval, pollingTimeUnit));201				} catch (InterruptedException e) {202					throw new TimeoutException("Sleep failed", e);203				}204			}205			logWarningMessageIfRequired(start);206			try {207				value = isTrue.apply();208				if (value != null && Boolean.class.equals(value.getClass())) {209					if (Boolean.TRUE.equals(value)) {210						return value;211					}212				} else if (value != null) {213					return value;214				}215			} catch (Throwable e) {216				lastException = propagateIfNotIngored(e);217			}218			attempts++;219		}220		221		if (returnResult) {222			return value;223		} else {224			String toAppend = hasMessage() ? " waiting for " + message : "";225			String timeoutMessage = String.format("Timed out after %s%s", timeout.toString().toLowerCase(), toAppend);226	227			throw new TimeoutException(timeoutMessage, lastException);228		}229	}230	private boolean hasMessage() {231		return message != null && !message.isEmpty();232	}233	private Throwable propagateIfNotIngored(Throwable e) {234		for (Class<? extends Throwable> ignoredException : ignoredExceptions) {235			if (ignoredException.isInstance(e)) {236				return e;237			}238		}239		throw Throwables.propagate(e);240	}241	private boolean hasMoreTime(Clock clock, long end) {242		return clock.isNowBefore(end);243	}244	private int getNextPollingInterval(Clock clock, long end) {245		long interval;246		if (attempts > pollingIntervals.size() - 1) {247			interval = pollingIntervals.get(pollingIntervals.size() - 1);248		} else {249			interval = pollingIntervals.get(attempts);250		}251		long currentTime = clock.now();252		long waitTime = currentTime + TimeUnit.MILLISECONDS.convert(interval, pollingTimeUnit);253		long stretchTime = waitTime + TimeUnit.MILLISECONDS.convert(interval / 2, pollingTimeUnit);254		// If going above timeout limit bring it back to that limit255		// If closer than half current interval stretch it out256		if (waitTime > end || stretchTime > end) {257			interval = pollingTimeUnit.convert(end - currentTime, TimeUnit.MILLISECONDS) + 1;258		}259		return (int)interval;260	}261	private void logWarningMessageIfRequired(long startTimeInMillis) {262		int interval;263		if (warnings > warningIntervals.size() - 1) {264			return;265		}266		interval = warningIntervals.get(warnings);267		long nextWarnTime = startTimeInMillis + TimeUnit.MILLISECONDS.convert(interval, warningTimeUnit);268		if (clock.now() >= nextWarnTime) {269			String toAppend = hasMessage() ? " waiting for " + message : "";			270			LOGGER.warn("Have been in waiting for over {} {}{}", interval, warningTimeUnit.toString(), toAppend);271			warnings++;272		}273	}274	/**275	 * Sleep for the requested time.276	 * 277	 * @param timeUnit TimeUnit278	 * @param duration Duration279	 */280	public static void pause(TimeUnit timeUnit, int duration) {281		try {282			Thread.sleep(timeUnit.toMillis(duration));283		} catch (InterruptedException e) {284			e.printStackTrace();285		}286	}287}...Source:ExpectedConditionsTest.java  
1package org.openqa.selenium.support.ui;2import static org.junit.Assert.assertSame;3import static org.junit.Assert.assertTrue;4import static org.junit.Assert.fail;5import static org.mockito.Mockito.times;6import static org.mockito.Mockito.verify;7import static org.mockito.Mockito.verifyZeroInteractions;8import static org.mockito.Mockito.when;9import static org.openqa.selenium.support.ui.ExpectedConditions.not;10import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf;11import org.junit.Before;12import org.junit.Test;13import org.junit.runner.RunWith;14import org.junit.runners.JUnit4;15import org.mockito.Mock;16import org.mockito.MockitoAnnotations;17import org.openqa.selenium.TimeoutException;18import org.openqa.selenium.WebDriver;19import org.openqa.selenium.WebElement;20import java.util.concurrent.TimeUnit;21/**22 * Tests for {@link ExpectedConditions}.23 */24@RunWith(JUnit4.class)25public class ExpectedConditionsTest {26  @Mock private WebDriver mockDriver;27  @Mock private WebElement mockElement;28  @Mock private Clock mockClock;29  @Mock private Sleeper mockSleeper;30  @Mock private GenericCondition mockCondition;31  private FluentWait<WebDriver> wait;32  @Before33  public void setUpMocks() {34    MockitoAnnotations.initMocks(this);35    wait = new FluentWait<WebDriver>(mockDriver, mockClock, mockSleeper)36        .withTimeout(1, TimeUnit.SECONDS)37        .pollingEvery(250, TimeUnit.MILLISECONDS);38  }39  @Test40  public void waitingForVisibilityOfElement_elementAlreadyVisible() {41    when(mockElement.isDisplayed()).thenReturn(true);42    assertSame(mockElement, wait.until(visibilityOf(mockElement)));43    verifyZeroInteractions(mockSleeper);44  }45  @Test46  public void waitingForVisibilityOfElement_elementBecomesVisible() throws InterruptedException {47    when(mockClock.laterBy(1000L)).thenReturn(3000L);48    when(mockClock.isNowBefore(3000L)).thenReturn(true);49    when(mockElement.isDisplayed()).thenReturn(false, false, true);50    assertSame(mockElement, wait.until(visibilityOf(mockElement)));51    verify(mockSleeper, times(2)).sleep(new Duration(250, TimeUnit.MILLISECONDS));52  }53  @Test54  public void waitingForVisibilityOfElement_elementNeverBecomesVisible()55      throws InterruptedException {56    when(mockClock.laterBy(1000L)).thenReturn(3000L);57    when(mockClock.isNowBefore(3000L)).thenReturn(true, false);58    when(mockElement.isDisplayed()).thenReturn(false, false);59    try {60      wait.until(visibilityOf(mockElement));61      fail();62    } catch (TimeoutException expected) {63      // Do nothing.64    }65    verify(mockSleeper, times(1)).sleep(new Duration(250, TimeUnit.MILLISECONDS));66  }67  @Test68  public void waitingForVisibilityOfElementInverse_elementNotVisible() {69    when(mockElement.isDisplayed()).thenReturn(false);70    assertTrue(wait.until(not(visibilityOf(mockElement))));71    verifyZeroInteractions(mockSleeper);72  }73  @Test74  public void waitingForVisibilityOfElementInverse_elementDisappears() throws InterruptedException {75    when(mockClock.laterBy(1000L)).thenReturn(3000L);76    when(mockClock.isNowBefore(3000L)).thenReturn(true);77    when(mockElement.isDisplayed()).thenReturn(true, true, false);78    assertTrue(wait.until(not(visibilityOf(mockElement))));79    verify(mockSleeper, times(2)).sleep(new Duration(250, TimeUnit.MILLISECONDS));80  }81  @Test82  public void waitingForVisibilityOfElementInverse_elementStaysVisible()83      throws InterruptedException {84    when(mockClock.laterBy(1000L)).thenReturn(3000L);85    when(mockClock.isNowBefore(3000L)).thenReturn(true, false);86    when(mockElement.isDisplayed()).thenReturn(true, true);87    try {88      wait.until(not(visibilityOf(mockElement)));89      fail();90    } catch (TimeoutException expected) {91      // Do nothing.92    }93    verify(mockSleeper, times(1)).sleep(new Duration(250, TimeUnit.MILLISECONDS));94  }95  @Test96  public void invertingAConditionThatReturnsFalse() {97    when(mockCondition.apply(mockDriver)).thenReturn(false);98    assertTrue(wait.until(not(mockCondition)));99    verifyZeroInteractions(mockSleeper);100  }101  @Test102  public void invertingAConditionThatReturnsNull() {103    when(mockCondition.apply(mockDriver)).thenReturn(null);104    assertTrue(wait.until(not(mockCondition)));105    verifyZeroInteractions(mockSleeper);106  }107  @Test108  public void invertingAConditionThatAlwaysReturnsTrueTimesout() throws InterruptedException {109    when(mockClock.laterBy(1000L)).thenReturn(3000L);110    when(mockClock.isNowBefore(3000L)).thenReturn(true, false);111    when(mockCondition.apply(mockDriver)).thenReturn(true);112    try {113      wait.until(not(mockCondition));114      fail();115    } catch (TimeoutException expected) {116      // Do nothing.117    }118    verify(mockSleeper, times(1)).sleep(new Duration(250, TimeUnit.MILLISECONDS));119  }120  @Test121  public void doubleNegatives_conditionThatReturnsFalseTimesOut() throws InterruptedException {122    when(mockClock.laterBy(1000L)).thenReturn(3000L);123    when(mockClock.isNowBefore(3000L)).thenReturn(true, false);124    when(mockCondition.apply(mockDriver)).thenReturn(false);125    try {126      wait.until(not(not(mockCondition)));127      fail();128    } catch (TimeoutException expected) {129      // Do nothing.130    }131    verify(mockSleeper, times(1)).sleep(new Duration(250, TimeUnit.MILLISECONDS));132  }133  @Test134  public void doubleNegatives_conditionThatReturnsNullTimesOut() throws InterruptedException {135    when(mockClock.laterBy(1000L)).thenReturn(3000L);136    when(mockClock.isNowBefore(3000L)).thenReturn(true, false);137    when(mockCondition.apply(mockDriver)).thenReturn(null);138    try {139      wait.until(not(not(mockCondition)));140      fail();141    } catch (TimeoutException expected) {142      // Do nothing.143    }144    verify(mockSleeper, times(1)).sleep(new Duration(250, TimeUnit.MILLISECONDS));145  }146  interface GenericCondition extends ExpectedCondition<Object> {}147}...Source:Sleeper.java  
1package org.openqa.selenium.support.ui;2import java.util.concurrent.TimeUnit;3public abstract interface Sleeper4{5  public static final Sleeper SYSTEM_SLEEPER = new Sleeper() {6    public void sleep(Duration duration) throws InterruptedException {7      Thread.sleep(duration.in(TimeUnit.MILLISECONDS));8    }9  };10  11  public abstract void sleep(Duration paramDuration)12    throws InterruptedException;13}...Interface Sleeper
Using AI Code Generation
1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.support.ui.Sleeper;3import org.openqa.selenium.support.ui.SystemClock;4import org.openqa.selenium.support.ui.WebDriverWait;5import org.openqa.selenium.support.ui.Wait;6import java.util.concurrent.TimeUnit;7public class SleeperClass {8public static void main(String[] args) {9WebDriver driver;10WebDriverWait wait;11Sleeper.SYSTEM_SLEEPER.sleep(new SystemClock(), 5000);12}13}14Sleeper.SYSTEM_SLEEPER.sleep(new SystemClock(), 5000);Interface Sleeper
Using AI Code Generation
1import org.openqa.selenium.support.ui.Sleeper;2import java.util.concurrent.TimeUnit;3public class SleeperClass {4public static void main(String[] args) throws InterruptedException {5Sleeper.SYSTEM_SLEEPER.sleep(new Duration(10, TimeUnit.SECONDS));6}7}8Sleeper sleeper = Sleeper.SYSTEM_SLEEPER;9sleeper.sleep(new Duration(10, TimeUnit.SECONDS));10Sleeper sleeper = Sleeper.SYSTEM_SLEEPER;11sleeper.sleep(new Duration(10, TimeUnit.SECONDS));Interface Sleeper
Using AI Code Generation
1import org.openqa.selenium.support.ui.Sleeper;2import java.util.concurrent.TimeUnit;3Sleeper.SYSTEM_SLEEPER.sleep(TimeUnit.SECONDS.toNanos(5));4import org.openqa.selenium.support.ui.Sleeper;5import java.util.concurrent.TimeUnit;6Sleeper.SYSTEM_SLEEPER.sleep(TimeUnit.SECONDS.toNanos(5));7import org.openqa.selenium.support.ui.Sleeper;8import java.util.concurrent.TimeUnit;9Sleeper.SYSTEM_SLEEPER.sleep(TimeUnit.SECONDS.toNanos(5));10import org.openqa.selenium.support.ui.Sleeper;11import java.util.concurrent.TimeUnit;12Sleeper.SYSTEM_SLEEPER.sleep(TimeUnit.SECONDS.toNanos(5));13import org.openqa.selenium.support.ui.Sleeper;14import java.util.concurrent.TimeUnit;15Sleeper.SYSTEM_SLEEPER.sleep(TimeUnit.SECONDS.toNanos(5));16import org.openqa.selenium.support.ui.Sleeper;17import java.util.concurrent.TimeUnit;18Sleeper.SYSTEM_SLEEPER.sleep(TimeUnit.SECONDS.toNanos(5));19import org.openqa.selenium.support.ui.Sleeper;20import java.util.concurrent.TimeUnit;21Sleeper.SYSTEM_SLEEPER.sleep(TimeUnit.SECONDS.toNanos(5));22import org.openqa.selenium.support.ui.Sleeper;23import java.util.concurrent.TimeUnit;24Sleeper.SYSTEM_SLEEPER.sleep(TimeUnit.SECONDS.toNanos(5));25import org.openqa.selenium.support.ui.Sleeper;26import java.util.concurrent.TimeUnit;27Sleeper.SYSTEM_SLEEPER.sleep(TimeUnit.SECONDS.toNanos(5));28import org.openqa.selenium.support.ui.Sleeper;29import java.util.concurrent.TimeUnitInterface Sleeper
Using AI Code Generation
1Sleeper.SYSTEM_SLEEPER.sleep(new Duration(2, TimeUnit.SECONDS));2Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)3		.withTimeout(30, TimeUnit.SECONDS)4		.pollingEvery(5, TimeUnit.SECONDS)5		.ignoring(NoSuchElementException.class);6WebElement foo = wait.until(new Function<WebDriver, WebElement>() {7	public WebElement apply(WebDriver driver) {8		return driver.findElement(By.id("foo"));9	}10});11public class MyElement implements WebElement, WrapsDriver {12	private final WebElement element;13	private final WebDriver driver;14	public MyElement(WebElement element, WebDriver driver) {15		this.element = element;16		this.driver = driver;17	}18	public void click() {19		element.click();20	}21	public void submit() {22		element.submit();23	}24	public void sendKeys(CharSequence... keysToSend) {25		element.sendKeys(keysToSend);26	}27	public void clear() {28		element.clear();29	}30	public String getTagName() {31		return element.getTagName();32	}33	public String getAttribute(String name) {34		return element.getAttribute(name);35	}36	public boolean isSelected() {37		return element.isSelected();38	}39	public boolean isEnabled() {40		return element.isEnabled();41	}42	public String getText() {43		return element.getText();44	}45	public List<WebElement> findElements(By by) {46		return element.findElements(by);47	}48	public WebElement findElement(By by) {49		return element.findElement(by);50	}51	public boolean isDisplayed() {52		return element.isDisplayed();53	}54	public Point getLocation() {55		return element.getLocation();56	}57	public Dimension getSize() {58		return element.getSize();59	}60	public Rectangle getRect() {61		return element.getRect();62	}63	public String getCssValue(String propertyName) {64		return element.getCssValue(propertyName);65	}66	public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {67		return element.getScreenshotAs(target);68	}69	public WebDriver getWrappedDriver() {70		return driver;71	}72}73public class MyElement implements WebElement, WrapsElement {74	private final WebElement element;75	public MyElement(WebElement element) {Interface Sleeper
Using AI Code Generation
1public class WaitTest {2    private WebDriver driver;3    private WebDriverWait wait;4    public void setUp() throws Exception {5        driver = new FirefoxDriver();6        wait = new WebDriverWait(driver, 30);7    }8    public void tearDown() throws Exception {9        driver.quit();10    }11    public void testWait() throws Exception {12        wait.until(ExpectedConditions.titleIs("Google"));13    }14}15public class WaitTest {16    private WebDriver driver;17    private WebDriverWait wait;18    public void setUp() throws Exception {19        driver = new FirefoxDriver();20        wait = new WebDriverWait(driver, 30);21    }22    public void tearDown() throws Exception {23        driver.quit();24    }25    public void testWait() throws Exception {26        wait.until(ExpectedConditions.titleIs("Google"));27    }28}29public class WaitTest {30    private WebDriver driver;31    private WebDriverWait wait;32    public void setUp() throws Exception {33        driver = new FirefoxDriver();34        wait = new WebDriverWait(driver, 30);35    }36    public void tearDown() throws Exception {37        driver.quit();38    }39    public void testWait() throws Exception {40        wait.until(ExpectedConditions.titleIs("Google"));41    }42}43public class WaitTest {44    private WebDriver driver;45    private WebDriverWait wait;46    public void setUp() throws Exception {47        driver = new FirefoxDriver();48        wait = new WebDriverWait(driver, 30);49    }50    public void tearDown() throws Exception {51        driver.quit();52    }53    public void testWait() throws Exception {54        wait.until(ExpectedConditions.titleIs("Google"));55    }56}1public static Optional<Fruit> find(String name, List<Fruit> fruits) {2   for (Fruit fruit : fruits) {3      if (fruit.getName().equals(name)) {4         return Optional.of(fruit);5      }6   }7   return Optional.empty();8}91String foo;2...3if( StringUtils.isBlank( foo ) ) {4   ///do something5}6LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!
