The other day I answered something similar to this, so that it is still fresh. The reason your code fails is because if the warning does not appear at the time the code is processed, it will in most cases fail.
Fortunately , the guys at Selenium WebDriver are already waiting for this to complete. For your code, as simple as doing it:
String alertText = ""; WebDriverWait wait = new WebDriverWait(driver, 5);
You can find all the APIs from ExpectedConditions here , and if you want the code behind this method here .
This code also solves the problem because you cannot return alert.getText () after closing the warning, so I save it in a variable for you.
source share