Best Selenium code snippet using org.openqa.selenium.support.decorators.WebDriverDecorator.createDecorated
Source:WebDriverDecorator.java
...81 * {@link #call(Decorated, Method, Object[])} and82 * {@link #onError(Decorated, Method, Object[], InvocationTargetException)}</li>83 * <li>if you want to modify behavior of a specific class instances only84 * (e.g. behaviour of WebElement instances) you can override one of the85 * overloaded <code>createDecorated</code> methods to create a non-trivial86 * decorator for the specific class only.</li>87 * </ul>88 * Let's consider both approaches by examples.89 * <p>90 * One of the most widely used decorator examples is a logging decorator.91 * In this case we want to add the same piece of logging code before and after92 * each invoked method:93 * <code>94 * public class LoggingDecorator extends WebDriverDecorator {95 * final Logger logger = LoggerFactory.getLogger(Thread.currentThread().getName());96 *97 * @Override98 * public void beforeCall(Decorated<?> target, Method method, Object[] args) {99 * logger.debug("before {}.{}({})", target, method, args);100 * }101 * @Override102 * public void afterCall(Decorated<?> target, Method method, Object[] args, Object res) {103 * logger.debug("after {}.{}({}) => {}", target, method, args, res);104 * }105 * }106 * </code>107 * For the second example let's implement a decorator that implicitly waits108 * for an element to be visible before any click or sendKeys method call.109 * <code>110 * public class ImplicitlyWaitingDecorator extends WebDriverDecorator {111 * private WebDriverWait wait;112 *113 * @Override114 * public Decorated<WebDriver> createDecorated(WebDriver driver) {115 * wait = new WebDriverWait(driver, Duration.ofSeconds(10));116 * return super.createDecorated(driver);117 * }118 * @Override119 * public Decorated<WebElement> createDecorated(WebElement original) {120 * return new DefaultDecorated<>(original, this) {121 * @Override122 * public void beforeCall(Method method, Object[] args) {123 * String methodName = method.getName();124 * if ("click".equals(methodName) || "sendKeys".equals(methodName)) {125 * wait.until(d -> getOriginal().isDisplayed());126 * }127 * }128 * };129 * }130 * }131 * </code>132 * This class is not a pure decorator, it allows to not only add new behavior133 * but also replace "normal" behavior of a WebDriver or derived objects.134 * <p>135 * Let's suppose you want to use JavaScript-powered clicks instead of normal136 * ones (yes, this allows to interact with invisible elements, it's a bad137 * practice in general but sometimes it's inevitable). This behavior change138 * can be achieved with the following "decorator":139 * <code>140 * public class JavaScriptPoweredDecorator extends WebDriverDecorator {141 * @Override142 * public Decorated<WebElement> createDecorated(WebElement original) {143 * return new DefaultDecorated<>(original, this) {144 * @Override145 * public Object call(Method method, Object[] args) throws Throwable {146 * String methodName = method.getName();147 * if ("click".equals(methodName)) {148 * JavascriptExecutor executor = (JavascriptExecutor) getDecoratedDriver().getOriginal();149 * executor.executeScript("arguments[0].click()", getOriginal());150 * return null;151 * } else {152 * return super.call(method, args);153 * }154 * }155 * };156 * }157 * }158 * </code>159 * It is possible to apply multiple decorators to compose behaviors added160 * by each of them. For example, if you want to log method calls and161 * implicitly wait for elements visibility you can use two decorators:162 * <code>163 * WebDriver original = new FirefoxDriver();164 * WebDriver decorated =165 * new ImplicitlyWaitingDecorator().decorate(166 * new LoggingDecorator().decorate(original));167 * </code>168 */169@Beta170public class WebDriverDecorator {171 private Decorated<WebDriver> decorated;172 public final WebDriver decorate(WebDriver original) {173 Require.nonNull("WebDriver", original);174 decorated = createDecorated(original);175 return createProxy(decorated);176 }177 public Decorated<WebDriver> getDecoratedDriver() {178 return decorated;179 }180 public Decorated<WebDriver> createDecorated(WebDriver driver) {181 return new DefaultDecorated<>(driver, this);182 }183 public Decorated<WebElement> createDecorated(WebElement original) {184 return new DefaultDecorated<>(original, this);185 }186 public Decorated<WebDriver.TargetLocator> createDecorated(WebDriver.TargetLocator original) {187 return new DefaultDecorated<>(original, this);188 }189 public Decorated<WebDriver.Navigation> createDecorated(WebDriver.Navigation original) {190 return new DefaultDecorated<>(original, this);191 }192 public Decorated<WebDriver.Options> createDecorated(WebDriver.Options original) {193 return new DefaultDecorated<>(original, this);194 }195 public Decorated<WebDriver.Timeouts> createDecorated(WebDriver.Timeouts original) {196 return new DefaultDecorated<>(original, this);197 }198 public Decorated<WebDriver.Window> createDecorated(WebDriver.Window original) {199 return new DefaultDecorated<>(original, this);200 }201 public Decorated<Alert> createDecorated(Alert original) {202 return new DefaultDecorated<>(original, this);203 }204 public Decorated<VirtualAuthenticator> createDecorated(VirtualAuthenticator original) {205 return new DefaultDecorated<>(original, this);206 }207 public void beforeCall(Decorated<?> target, Method method, Object[] args) {}208 public Object call(Decorated<?> target, Method method, Object[] args) throws Throwable {209 return decorateResult(method.invoke(target.getOriginal(), args));210 }211 public void afterCall(Decorated<?> target, Method method, Object[] args, Object res) {}212 public Object onError(Decorated<?> target, Method method, Object[] args,213 InvocationTargetException e) throws Throwable214 {215 throw e.getTargetException();216 }217 private Object decorateResult(Object toDecorate) {218 if (toDecorate instanceof WebDriver) {219 return createProxy(getDecoratedDriver());220 }221 if (toDecorate instanceof WebElement) {222 return createProxy(createDecorated((WebElement) toDecorate));223 }224 if (toDecorate instanceof Alert) {225 return createProxy(createDecorated((Alert) toDecorate));226 }227 if (toDecorate instanceof VirtualAuthenticator) {228 return createProxy(createDecorated((VirtualAuthenticator) toDecorate));229 }230 if (toDecorate instanceof WebDriver.Navigation) {231 return createProxy(createDecorated((WebDriver.Navigation) toDecorate));232 }233 if (toDecorate instanceof WebDriver.Options) {234 return createProxy(createDecorated((WebDriver.Options) toDecorate));235 }236 if (toDecorate instanceof WebDriver.TargetLocator) {237 return createProxy(createDecorated((WebDriver.TargetLocator) toDecorate));238 }239 if (toDecorate instanceof WebDriver.Timeouts) {240 return createProxy(createDecorated((WebDriver.Timeouts) toDecorate));241 }242 if (toDecorate instanceof WebDriver.Window) {243 return createProxy(createDecorated((WebDriver.Window) toDecorate));244 }245 if (toDecorate instanceof List) {246 return ((List<?>) toDecorate).stream()247 .map(this::decorateResult)248 .collect(Collectors.toList());249 }250 return toDecorate;251 }252 protected final <Z> Z createProxy(final Decorated<Z> decorated) {253 Set<Class<?>> decoratedInterfaces = extractInterfaces(decorated);254 Set<Class<?>> originalInterfaces = extractInterfaces(decorated.getOriginal());255 final InvocationHandler handler = (proxy, method, args) -> {256 try {257 if (method.getDeclaringClass().equals(Object.class)...
Source:WaitHelper.java
...20 WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);21 return wait.until(ExpectedConditions.visibilityOf(element));22 }23 @Override24 public Decorated<WebDriver> createDecorated(WebDriver driver) {25 wait = new WebDriverWait(driver, Duration.ofSeconds(10));26 return super.createDecorated(driver);27 }28 @Override29 public Decorated<WebElement> createDecorated(WebElement original) {30 return new DefaultDecorated<WebElement>(original, this) {31 @Override32 public void beforeCall(Method method, Object[] args) {33 String methodName = method.getName();34 if ("click".equals(methodName) || "sendKeys".equals(methodName)) {35 wait.until(d -> getOriginal().isDisplayed());36 }37 }38 };39 }40 }...
Source:WindowDecorator.java
...12public class WindowDecorator extends WebDriverDecorator {13 private Decorated<WebDriver.Window> decorated;14 public final WebDriver.Window decorate(WebDriver.Window original) {15 Require.nonNull("WebDriver.Window", original);16 decorated = createDecorated(original);17 return createProxy(decorated);18 }19}...
createDecorated
Using AI Code Generation
1package test;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory;4import org.openqa.selenium.support.pagefactory.DefaultElementLocatorFactory;5import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;6import org.openqa.selenium.support.pagefactory.FieldDecorator;7import org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler;8import java.lang.reflect.Field;9import java.lang.reflect.InvocationHandler;10import java.lang.reflect.Method;11import java.lang.reflect.Proxy;12public class WebDriverDecorator extends WebDriverDecoratorBase {13 public WebDriverDecorator(WebDriver driver) {14 super(driver);15 }16 public WebDriver createDecorated(ClassLoader loader, Class<?>[] interfaces) {17 InvocationHandler handler = new WebDriverDecoratorInvocationHandler(driver);18 return (WebDriver) Proxy.newProxyInstance(loader, interfaces, handler);19 }20 public static class WebDriverDecoratorInvocationHandler implements InvocationHandler {21 private final WebDriver driver;22 private final ElementLocatorFactory factory;23 public WebDriverDecoratorInvocationHandler(WebDriver driver) {24 this.driver = driver;25 this.factory = new AjaxElementLocatorFactory(driver, 10);26 }27 public Object invoke(Object object, Method method, Object[] objects) throws Throwable {28 if (method.getName().equals("toString")) {29 return "WebDriverDecorator for " + driver;30 }31 if (method.getName().equals("getWrappedDriver")) {32 return driver;33 }34 if (method.getName().equals("getWrappedElement")) {35 return objects[0];36 }37 Object result = method.invoke(driver, objects);38 if (result != null) {39 return result;40 }41 FieldDecorator decorator = new WebDriverDecoratorFieldDecorator(driver, factory);42 for (Class<?> iface : driver.getClass().getInterfaces()) {43 result = decorateTheFields(iface, decorator, objects);44 if (result != null) {45 return result;46 }47 }48 return null;49 }50 private Object decorateTheFields(Class<?> iface, FieldDecorator decorator, Object[] objects) {51 for (Field field : iface.getDeclaredFields()) {52 if (field.getType().isAssignableFrom(method.getReturnType())) {53 if (objects == null || objects.length == 0) {54 return decorator.decorate(driver.getClass().getClassLoader(), field);55 } else {56 return decorator.decorate(objects[0].getClass().getClassLoader(), field);57 }58 }59 }60 return null;61 }62 }
createDecorated
Using AI Code Generation
1package com.knoldus;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.support.PageFactory;7import org.openqa.selenium.support.decorators.WebDriverDecorator;8import org.openqa.selenium.support.pagefactory.DefaultElementLocatorFactory;9import org.openqa.selenium.support.pagefactory.DefaultFieldDecorator;10import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;11import org.openqa.selenium.support.ui.ExpectedConditions;12import org.openqa.selenium.support.ui.WebDriverWait;13import java.util.List;14import java.util.concurrent.TimeUnit;15public class Main {16 public static void main(String[] args) {17 WebDriver driver = new ChromeDriver();18 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);19 ElementLocatorFactory factory = new DefaultElementLocatorFactory(driver);20 DefaultFieldDecorator decorator = new DefaultFieldDecorator(factory);21 WebDriver decoratedDriver = new WebDriverDecorator(decorator).decorate(driver);22 GoogleSearchPage page = PageFactory.initElements(decoratedDriver, GoogleSearchPage.class);23 page.searchFor("Knoldus");24 }25}26class GoogleSearchPage {27 private WebDriver driver;28 @FindBy(css = "input[name=q]")29 private WebElement searchBox;30 @FindBy(css = "input[name=btnK]")31 private WebElement searchButton;32 @FindBy(css = "div[id=resultStats]")33 private WebElement resultStats;34 public GoogleSearchPage(WebDriver driver) {35 this.driver = driver;36 }37 public void searchFor(String text) {38 searchBox.sendKeys(text);39 searchButton.click();40 new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOf(resultStats));41 }42}43Recommended Posts: How to use PageFactory.initElements() method to initialize the elements of a class using the WebDriverFieldDecorator object?
createDecorated
Using AI Code Generation
1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.chrome.ChromeDriver;3import org.openqa.selenium.support.PageFactory;4import org.openqa.selenium.support.decorators.WebDriverDecorator;5import org.openqa.selenium.support.decorators.WebDriverDecorators;6public class DecoratorExample {7 public static void main(String[] args) {8 WebDriver driver = new ChromeDriver();9 WebDriver decoratedDriver = WebDriverDecorators.createDecorated(driver);10 Page page = PageFactory.initElements(decoratedDriver, Page.class);11 page.doSomething();12 }13}14package com.automationrhapsody.decorator;15import org.openqa.selenium.WebDriver;16import org.openqa.selenium.support.PageFactory;17public class Page {18 private WebDriver driver;19 public Page(WebDriver driver) {20 this.driver = driver;21 PageFactory.initElements(driver, this);22 }23 public void doSomething() {24 System.out.println("Page.doSomething() invoked");25 System.out.println("driver: " + driver);26 }27}28Page.doSomething() invoked
createDecorated
Using AI Code Generation
1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.support.decorators.WebDriverDecorator;3import org.openqa.selenium.support.decorators.WebDriverDecorators;4public class DecoratorDemo {5 public static void main(String[] args) {6 WebDriver driver = WebDriverDecorators.createDecorated(new ChromeDriver(), new WebDriverDecorator() {7 public void beforeNavigateTo(String url, WebDriver driver) {8 System.out.println("Before navigating to: '" + url + "'");9 }10 });11 driver.quit();12 }13}14import org.openqa.selenium.WebDriver;15import org.openqa.selenium.chrome.ChromeDriver;16import org.openqa.selenium.support.decorators.WebDriverDecorator;17import org.openqa.selenium.support.decorators.WebDriverDecorators;18import org.seleniumhq.selenium.fluent.FluentWebDriver;19import java.util.ServiceLoader;20public class WebDriverFactoryDecoratorDemo {21 public static void main(String[] args) {22 ServiceLoader<WebDriverFactory> loader = ServiceLoader.load(WebDriverFactory.class);23 WebDriverFactory factory = loader.iterator().next();24 WebDriver driver = factory.getDriver();25 driver.quit();26 }27 public static class WebDriverFactoryDecorator implements WebDriverFactory {28 public WebDriver getDriver() {29 return WebDriverDecorators.createDecorated(new ChromeDriver(), new WebDriverDecorator() {30 public void beforeNavigateTo(String url, WebDriver driver) {31 System.out.println("Before navigating to: '" + url + "'");32 }33 });34 }35 }36}
createDecorated
Using AI Code Generation
1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.support.PageFactory;3import org.openqa.selenium.support.decorators.WebDriverDecorator;4public class DecoratorDemo {5 public static void main(String[] args) {6 WebDriver driver = new ChromeDriver();7 WebDriverDecorator decorator = new WebDriverDecorator(driver);8 PageFactory.initElements(decorator.createDecorated(driver), this);9 }10}11import org.openqa.selenium.WebDriver;12import org.openqa.selenium.support.PageFactory;13import org.openqa.selenium.support.decorators.WebDriverDecorator;14public class DecoratorDemo {15 public static void main(String[] args) {16 WebDriver driver = new ChromeDriver();17 WebDriverDecorator decorator = new WebDriverDecorator(driver);18 System.out.println(decorator.isDecorated(driver));19 }20}21import org.openqa.selenium.WebDriver;22import org.openqa.selenium.support.PageFactory;23import org.openqa.selenium.support.decorators.WebDriverDecorator;24public class DecoratorDemo {25 public static void main(String[] args) {26 WebDriver driver = new ChromeDriver();
createDecorated
Using AI Code Generation
1public class WebDriverDecorator {2public static WebDriver createDecorated(WebDriver driver, Class<? extends Annotation> annotation) {3 return createDecorated(driver, annotation, new DefaultElementLocatorFactory(driver));4}5public static WebDriver createDecorated(WebDriver driver, Class<? extends Annotation> annotation, ElementLocatorFactory factory) {6 return createDecorated(driver, annotation, factory, new DefaultElementLocatorFactory(driver));7}8public static WebDriver createDecorated(WebDriver driver, Class<? extends Annotation> annotation, ElementLocatorFactory factory, ElementLocatorFactory pageFactory) {9 WebDriver proxy = (WebDriver) Proxy.newProxyInstance(WebDriverDecorator.class.getClassLoader(), new Class[]{WebDriver.class, JavascriptExecutor.class, TakesScreenshot.class}, new WebDriverDecorator(driver, annotation, factory, pageFactory));10 return proxy;11}12private WebDriver driver;13private Class<? extends Annotation> annotation;14private ElementLocatorFactory factory;15private ElementLocatorFactory pageFactory;16private WebDriverDecorator(WebDriver driver, Class<? extends Annotation> annotation, ElementLocatorFactory factory, ElementLocatorFactory pageFactory) {17 this.driver = driver;18 this.annotation = annotation;19 this.factory = factory;20 this.pageFactory = pageFactory;21}22public Object invoke(Object object, Method method, Object[] objects) throws Throwable {23 if (method.getName().equals("getWrappedDriver")) {24 return driver;25 }26 if (method.getName().equals("getWrappedElement")) {27 return objects[0];28 }29 if (method.getName().equals("getWrappedElements")) {30 return objects[0];31 }32 if (method.getName().equals("getWrappedLocator")) {33 return objects[0];34 }35 if (method.getName().equals("getWrappedLocators")) {36 return objects[0];37 }38 if (method.getName().equals("getWrappedSearchContext")) {39 return objects[0];40 }41 if (method.getName().equals("getWrappedSearchContexts")) {42 return objects[0];43 }44 if (method.getName().equals("getWrappedElementLocator")) {45 return objects[0];46 }47 if (method.getName().equals("getWrappedElementLocators")) {48 return objects[0];49 }50 if (method.getName().equals("getWrappedPageFactory")) {51 return objects[0];52 }53 if (method.getName().equals("getWrappedPage")) {54 return objects[0];55 }56 if (method.getName().equals("getWrappedPages"))
LambdaTest’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!!