If you don't need to check whether the alert actually appears, I would recommend changing the behavior of the JavaScript alert()
method to log a message instead:
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver;
javascriptExecutor.executeScript("window.alert = function(message){ console.log(message); };" +
"window.confirm = function(message){ console.log(message); return true; };");
Then you can skip HtmlUnitDriver.switchTo().alert().accept()
in your code.
Note: This method won't work if the alert appears on the initial page load since Selenium waits for the page to be loaded before interacting with it. So the above JavaScript will be executed too late.
As of HtmlUnitDriver
version 2.25
, HtmlUnitDriver.switchTo().alert().accept()
no longer throws an UnsupportedOperationException()
. However, accept()
appears to do nothing except confirm that the alert is present. Since the alert cannot be dismissed, turning off alerts using the above method is probably the best/only solution. If you must test alerts with HtmlUnitDriver
, you may need two separate tests---one for checking that the alert appears and another for checking that the browser behaves correctly when the alert is disabled.
If you desperately need alert handing and you are okay with building from source, alert handling has been implemented in the master
branch of HtmlUnitDriver
. I'm not sure when it will be included in a release, though.