如何在 selenium 页面对象模型中处理 confirm box/message

How to handle confirm box/message in selenium Page Object Model

我开始学习POM,我无法切换到确认框。

下面是没有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();
    }
}

在上面的代码中,我很容易使用驱动程序对象处理确认框。但是,在 POM 中,驱动程序对象实际上对 class 不可用。下面是带有 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();
    }
}

如何处理 clickConfirmButton 方法中的确认框?

这是 DriverInitiator 的样子。

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;
    }
    
}

试试这个,看看这个是否适合你,

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();
    }
}