Abhi
Abhi

Reputation: 29

Handling alerts using if/else in Java

How to handle the alerts using if/else commands? If alerts comes up do accept/dismiss, if not proceed further. I was trying with below code but an error at (r==true) says incompatible type.

bool r = driver.findElement(By.xpath("//div[contains(text(),'javax.baja.sys.ActionInvokeException')]"));
if (r = true) {
    driver.switchTo().alert().accept();
} else {
    Actions click2 = new Actions(driver);
    WebElement dclick2 = driver.findElement(By.xpath(".//span[text()='Bluemix_As_Device']"));
    click2.moveToElement(dclick2).doubleClick().build().perform();
}

Upvotes: 0

Views: 3020

Answers (3)

SeJaPy
SeJaPy

Reputation: 294

driver.findElements will check the existence of the object and will return 1 if exist else zero.
So in your case though the alert exist or not, it will handle and based on size it will execute next step. Hope this helps in your case.

int r= driver.findElements(By.xpath("//div[contains(text(),'javax.baja.sys.ActionInvokeException')]")).size();
if(r!=0){
    driver.switchTo().alert().accept();
} else {
    Actions click2 = new Actions(driver);
    WebElement dclick2 = driver.findElement(By.xpath(".//span[text()='Bluemix_As_Device']"));
    click2.moveToElement(dclick2).doubleClick().build().perform();
}

Upvotes: 0

Naman
Naman

Reputation: 31878

The incompatible type is for the reason that

driver.findElement 

would return a WebElement type and not a boolean(that's java). You might want to change the code to:

try {
    WebElement r = driver.findElement(By.xpath("//div[contains(text(),'javax.baja.sys.ActionInvokeException')]"));
    driver.switchTo().alert().accept(); // this would be executed only if above element is found
} catch (NoSuchElementException ex) {
    // since the element was not found, I 'm still doing some stuff
    Actions click2 = new Actions(driver);
    WebElement dclick2 = driver.findElement(By.xpath(".//span[text()='Bluemix_As_Device']"));
    click2.moveToElement(dclick2).doubleClick().build().perform();
}

Upvotes: 1

Abhishek Honey
Abhishek Honey

Reputation: 645

As r is of boolean type so there is no need to write if(r == true) or if(r == false) you can directly write if(r) and java will understand the code.

Upvotes: 0

Related Questions