Sha*_*dan 17 javascript java selenium exception selenium-webdriver
我正在使用Chrome驱动程序并尝试测试网页.
通常它运行正常,但有一段时间我得到例外 -
org.openqa.selenium.UnhandledAlertException: unexpected alert open
(Session info: chrome=38.0.2125.111)
(Driver info: chromedriver=2.9.248315,platform=Windows NT 6.1 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 16 milliseconds: null
Build info: version: '2.42.2', revision: '6a6995d', time: '2014-06-03 17:42:30'
System info: host: 'Casper-PC', ip: '10.0.0.4', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.8.0_25'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Run Code Online (Sandbox Code Playgroud)
然后我试着处理警报 -
Alert alt = driver.switchTo().alert();
alt.accept();
Run Code Online (Sandbox Code Playgroud)
但这次我复活了 - org.openqa.selenium.NoAlertPresentException
我附上警报的屏幕截图 -


我现在无法弄明白该做什么.问题是我总是没有收到这个例外.当它发生时,测试失败.
Rot*_*otS 25
我也有这个问题.这是由于驱动程序遇到警报时的默认行为.默认行为设置为"ACCEPT",因此警报自动关闭,并且switchTo().alert()找不到它.
解决方案是修改驱动程序的默认行为("IGNORE"),以便它不会关闭警报:
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
d = new FirefoxDriver(dc);
Run Code Online (Sandbox Code Playgroud)
然后你可以处理它:
try {
click(myButton);
} catch (UnhandledAlertException f) {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println("Alert data: " + alertText);
alert.accept();
} catch (NoAlertPresentException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用WaitSelenium WebDriver 中的功能来等待警报,并在警报可用时接受它。
在 C# 中 -
public static void HandleAlert(IWebDriver driver, WebDriverWait wait)
{
if (wait == null)
{
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
}
try
{
IAlert alert = wait.Until(drv => {
try
{
return drv.SwitchTo().Alert();
}
catch (NoAlertPresentException)
{
return null;
}
});
alert.Accept();
}
catch (WebDriverTimeoutException) { /* Ignore */ }
}
Run Code Online (Sandbox Code Playgroud)
它在 Java 中的等价物 -
public static void HandleAlert(WebDriver driver, WebDriverWait wait) {
if (wait == null) {
wait = new WebDriverWait(driver, 5);
}
try {
Alert alert = wait.Until(new ExpectedCondition<Alert>{
return new ExpectedCondition<Alert>() {
@Override
public Alert apply(WebDriver driver) {
try {
return driver.switchTo().alert();
} catch (NoAlertPresentException e) {
return null;
}
}
}
});
alert.Accept();
} catch (WebDriverTimeoutException) { /* Ignore */ }
}
Run Code Online (Sandbox Code Playgroud)
它会等待 5 秒,直到出现警报,如果预期的警报不可用,您可以捕获异常并进行处理。
| 归档时间: |
|
| 查看次数: |
59340 次 |
| 最近记录: |