Selenium LoadableComponent加载组件

继承LoadableComponent类可以在打开地址时,

判断浏览器是否打开了预期的网址,

需要重写load()与isLoad()方法;

即使没有定义get()方法,

也可以进行get()方法的调用,

get()方法会默认调用页面对象类中的load()方法。

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.LoadableComponent;
import org.testng.Assert;

public class BaiduHomePage extends LoadableComponent<BaiduHomePage> {
    //百度首页的页面工厂

    @FindBy(xpath = ".//*[@id='kw']")
    private WebElement inputBox;
    //输入框

    @FindBy(xpath = ".//*[@id='su']")
    private WebElement searchButton;
    //搜索按钮

    @FindBy(xpath = ".//*[@id='1']/h3/a")
    private WebElement encyclopedia;
    //中国_百度百科元素

    private String baiduUrl = "https://www.baidu.com/";
    //百度首页的地址

    private String baiduOnce = "百度一下,你就知道";
    //百度首页的标题

    private WebDriver driver;

    public BaiduHomePage(){
        //构造函数,生成浏览器对象,初始化PageFactory对象
        System.setProperty("webdriver.firefox.marionette", "src/main/resourcec/geckodriver.exe");
        driver = new FirefoxDriver();
        PageFactory.initElements(driver, this);
    }

    @Override
    protected void load() {
        //打开百度
        driver.get(baiduUrl);
        driver.manage().window().maximize();
    }

    @Override
    protected void isLoaded() throws Error{
        //断言浏览器是否打开了正确的网址
        Assert.assertTrue(driver.getTitle().equals(baiduOnce));
    }

    public void quit(){
        //结束driver
        driver.quit();
    }

    public void searchChina(){
        //封装搜索“中国”的步骤
        inputBox.sendKeys("中国");
        //输入“中国”
        searchButton.click();
        //点击搜索按钮
    }

    public String getText(){
        //封装获取中国_百度百科元素的文本
        return encyclopedia.getText();
    }
}

import org.testng.Assert;
import org.testng.annotations.Test;

public class BaiduSearchCase {

    @Test
    //搜索“中国”的测试用例
    public void baiduSearch() throws InterruptedException {
        BaiduHomePage baiduHomePage = new BaiduHomePage();
        //生成一个BaiduHomePage对象实例

        baiduHomePage.get();
        baiduHomePage.searchChina();
        Thread.sleep(2000);

        Assert.assertEquals(baiduHomePage.getText(), "中国_百度百科");
        baiduHomePage.quit();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值