gpt4 book ai didi

selenium - 实现全局监听器以暂停代码执行

转载 作者:行者123 更新时间:2023-12-04 08:12:24 26 4
gpt4 key购买 nike

我有这段代码用于暂停 Selenium 代码的执行:Boolean waitruntil = new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[@class='ngx-loading-text center-center' and starts-with(., 'Loading')]")));我让每个测试都运行到 JUnit 代码中。你知道我如何实现一个全局监听器,如果显示加载栏,它会暂停代码执行(使用 Xpath 定位器检测)

最佳答案

一种比使用监听器更复杂的解决方案是使用代理包装您的元素,并在您点击代理时执行检查。
让监听器监听事件而不改变测试流程,
首先,我们需要创建一个在调用元素时执行检查的类:

public class ElementProxy implements InvocationHandler {

private final WebElement element;

public ElementProxy(WebElement element) {
this.element = element;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
this.waitForPageLoad();
return method.invoke(element, args);
}

private void waitForPageLoad() {
WebDriver driver = ((WrapsDriver) element).getWrappedDriver();
WebElement loadingBar = driver.findElement(By.xpath("//div[@class='ngx-loading-text center-center' and starts-with(., 'Loading')]"));
new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOfElement(loadingBar))
}

public static WebElement proxy(WebElement element) {
ElementProxy proxy = new ElementProxy(element);
WebElement wrappdElement = (WebElement) Proxy.newProxyInstance(ElementProxy.class.getClassLoader(),
new Class[] { WebElement.class },
proxy);
return wrappdElement;
}

}
然后您可以调用 ElementProxy.proxy(element)这将返回一个新的代理元素,类似于 PageFactory 的行为在引擎盖下。
最后一件事是将其包裹在您自己的 PageFactory下所以你可以控制元素的行为:
public class MyPageFactory {

public static <T> void initElements(WebDriver driver, T pageObject) {
PageFactory.initElements(driver, pageObject);

for (Field field : pageObject.getClass().getDeclaredFields()) {
if (field.getType().equals(WebElement.class)) {
boolean accessible = field.isAccessible();
field.setAccessible(true);

field.set(pageobject, ElementProxy.proxy((WebElement) field.get(pageObject)));
field.setAccessible(accessible);
}
}

}

}
现在,如果您在存在加载栏的网页中,请使用新的 MyPageFactory ,它将自动执行检查。
如果您不需要执行检查,请使用常规 PageFactory .
引用: https://www.vinsguru.com/selenium-webdriver-how-to-handle-annoying-random-popup-alerts/

关于selenium - 实现全局监听器以暂停代码执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65887751/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com