Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.openqa.selenium.UnhandledAlertException: unexpected alert open

Tags:

I am using a Chrome Driver and trying to test a webpage.

Normally it runs fine, but sometimes I get exceptions:

 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 

Then I tried to handle the alert:

  Alert alt = driver.switchTo().alert();   alt.accept(); 

But this time I received:

org.openqa.selenium.NoAlertPresentException  

I am attaching the screenshots of the alert: First Alert and by using esc or enter i gets the second alertSecond Alert

I am not able to figure out what to do now. The problem is that I do not always receive this exception. And when it occurs, the test fails.

like image 433
Shantanu Nandan Avatar asked Nov 06 '14 06:11

Shantanu Nandan


1 Answers

I had this problem too. It was due to the default behaviour of the driver when it encounters an alert. The default behaviour was set to "ACCEPT", thus the alert was closed automatically, and the switchTo().alert() couldn't find it.

The solution is to modify the default behaviour of the driver ("IGNORE"), so that it doesn't close the alert:

DesiredCapabilities dc = new DesiredCapabilities(); dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE); d = new FirefoxDriver(dc); 

Then you can handle it:

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();     } } 
like image 56
RotS Avatar answered Oct 15 '22 07:10

RotS