I started learning POM and I'm unable to switch to confirm box.
Below is the code without POM.
public class SimpleConfirmTestCase {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path to driver);
WebDriver driver = new ChromeDriver();
driver.get("path to html file");
driver.findElement(By.id("confirmButton")).click();
//handling confirm box
Alert confirmBox = driver.switchTo().alert();
confirmBox.accept();
// driver.close();
// driver.quit();
}
}
In the above code, I'm easily handling the confirm box using the driver object. However, in POM, the driver object is not actually available to the class. Below is the code with POM.
public class POMConfirmTest {
@FindBy(id = "confirmButton")
private WebElement confirmButton;
public POMConfirmTest(WebDriver driver) {
PageFactory.initElements(driver, this);
}
public void clickConfirmButton() {
confirmButton.click();
//here goes the code to handle the confirm message
}
}
public class TestExecuter {
public static void main(String[] args) {
WebDriver driver = DriverInitiator.getDriver("chrome");
POMConfirmTest pomConfirmTest = new POMConfirmTest(driver);
pomConfirmTest.clickConfirmButton();
}
}
How can I handle the confirm box in clickConfirmButton method?
This is how DriverInitiator looks.
private DriverInitiator() {}
public static WebDriver getDriver(String name) {
WebDriver driver = null;
WebDriver chrome = null;
//creating chrome driver
if(name.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "path");
if(chrome == null) {
chrome = new ChromeDriver();
}
driver = chrome;
}
return driver;
}
}
CodePudding user response:
Try this one and see if this one works for you,
public class POMConfirmTest {
WebDriver driver;
@FindBy(id = "confirmButton")
private WebElement confirmButton;
public POMConfirmTest(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void clickConfirmButton() {
confirmButton.click();
Alert confirmBox = driver.switchTo().alert();
confirmBox.accept();
\\handling the confirm box in the same function
}
}
public class TestExecuter {
public static void main(String[] args) {
WebDriver driver = DriverInitiator.getDriver("chrome");
POMConfirmTest pomConfirmTest = new POMConfirmTest(driver);
pomConfirmTest.clickConfirmButton();
}
}