4

else is perfectly executed but if block is not executed - can anyone help me?

WebDriverWait wait = new WebDriverWait(Maf_Base.getDriver(), 10 /*timeout in seconds*/);

if(wait.until(ExpectedConditions.alertIsPresent())==null) {  
    System.out.println("alert was not present");
    agobj.logout.click();
} else {
    Alert alert = Maf_Base.getDriver().switchTo().alert();
    alert.accept();
    System.out.println("alert was present and accepted");
}
  • 2
    Two thoughts - is an alert actually present? - Is waiting until alertISPresent to be null just timing out after 10 seconds? – Michael Durrant Mar 20 at 9:39
4

Try a try catch, if something in the try gives a timeout exception (e.g. alert not found) it will execute the code in the catch block.

WebDriverWait wait = new WebDriverWait(Maf_Base.getDriver(), 10);

try {
    wait.until(ExpectedConditions.alertIsPresent())
    Alert alert = Maf_Base.getDriver().switchTo().alert();
    alert.accept();
    System.out.println("alert was present and accepted");
catch(Exception e) {
    System.out.println("alert was not present");
    System.out.print(e);
    agobj.logout.click();
}
  • "Thus it reads: if(functionObject == null) {} and a functionObject is not null it is a Object." it is not actually true (if I got you right). ExpectedConditions.alertIsPresent() is "function object" but not wait.until(functionObject). So it does not read if(functionObject == null) {} but rather if(alert==null) where alert is a product of functionObject.apply() that is called inside until method. However alert cannot be null since until just throw an exception if it would be null. However I agree with general idea of looking up the alert. – Alexey R. Mar 20 at 10:02
  • @AlexeyR. I am not a Java expert, but the wait.until returns an alert, but while it is waiting it is not an alert. An IF comparison in most languages do not wait for the return of a function, it just compares the objects in its current state. Still the try/catch will probably solve the issue. – Niels van Reijmersdal Mar 20 at 10:45
  • 1
    @AlexeyR. Removed my assumption of how Java works :) – Niels van Reijmersdal Mar 20 at 10:47
  • @NielsvanReijmersdal thanks, bro!! it's working properly – anjith neerukonda Mar 20 at 12:50
3

If you check wait.until() code:

enter image description here

You will know that it never returns null. It either returns found alert (see lines 88-92) or throws an exception. This is why your if does not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.