java + selenium测试框架(之测试驱动) 版本演化三

java + selenium测试框架(之测试驱动) 版本演化三

本节将使用properity文件来管理程序的设置,并且完成Test的基类,用于辅助测试。

增加初始化WebDriver的代码

项目中增加配置文件

在工程项目的resource下面,增加一个配置文件(selenium-vars.properties):

#WebDriverTypes or Browser to be tested: InternetExplorer  Firefox   Chrome
webdriver.type=Firefox

#Path of ChromeDriver 
webdriver.chrome.driver.path=lib/chromedriver.exe

#Path of IEDriver
webdriver.ie.driver.path=lib/IEDriverServer.exe

读取和保存配置

然后用ConfigurationSettings来保存这些配置变量:

public class ConfigurationSettings {

        private static Properties props = null;

        private final static String SELENIUM_CONFIG="selenium-vars.properties";

        static{
            try {
                props = new Properties();
                InputStream in = ConfigurationSettings.class.getClassLoader().getResourceAsStream(SELENIUM_CONFIG);
                props.load(in);
            } catch (Exception e) {
                throw new RuntimeException("ConfigurationSettings initialize failed.", e);
            }
        }

        public static String getProperty(String propertyName){
            return props.getProperty(propertyName);
        }

        /**
         * WebDriver类型
         */
        public static final String WEBDRIVER_TYPE = getProperty("webdriver.type").trim();

        /**
         * IEdriver的路径
         */
        public static final String WEBDRIVER_IE_DRIVER_PATH = getProperty("webdriver.ie.driver.path").trim();

        /**
         * Chromedriver的路径
         */
        public static final String WEBDRIVER_CHROME_DRIVER_PATH  = getProperty("webdriver.chrome.driver.path").trim();

}

用DriverFactory完成初始化

下面,完成驱动程序的初始化:

public class DriverFactory {
    private static DriverType DEFAULT_DRIVER_TYPE = DriverType.Firefox;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    private static DriverFactory instance = null;

    static {
        instance = new DriverFactory();
    }

    public static DriverFactory getInstance() {
        return instance;
    }

    public WebDriver getDriver() {
        DriverType type = DEFAULT_DRIVER_TYPE;
        try {
            type = Enum.valueOf(DriverType.class, ConfigurationSettings.WEBDRIVER_TYPE);
        }
        catch (Exception ex) {
            logger.warn("Parse WebDriver.Type failed, use default driver type: " + DEFAULT_DRIVER_TYPE.name());
            logger.debug(ex.getMessage(), ex);
        }
        return type.getDriver();
    }
}

对应的DriverType中负责实际的驱动程序初始化:

public enum DriverType {
    InternetExplorer {

        @Override
        public WebDriver getDriver() {

            if (!StringUtils.isEmpty(ConfigurationSettings.WEBDRIVER_IE_DRIVER_PATH)) {
                System.setProperty(InternetExplorerDriverService.IE_DRIVER_EXE_PROPERTY,ConfigurationSettings.WEBDRIVER_IE_DRIVER_PATH);
            }

            DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
            ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);

            return new InternetExplorerDriver(ieCapabilities);
        }
    },
    Firefox {
        @Override
        public WebDriver getDriver() {
            return new FirefoxDriver();
        }
    },
    Chrome {
        @Override
        public WebDriver getDriver() {

            if (!StringUtils.isEmpty(ConfigurationSettings.WEBDRIVER_CHROME_DRIVER_PATH)) {
                System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY,ConfigurationSettings.WEBDRIVER_CHROME_DRIVER_PATH);
            }
            return new ChromeDriver();
        }
    };
    public abstract WebDriver getDriver();
}

完成TestBase

public abstract class TestBase {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    protected WebDriver driver = null;

    /**
     * 用于硬性的等待
     * @param seconds
     */
    public void sleep(int seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    @BeforeClass(alwaysRun = true)
    public void setUpTestBase(ITestContext testContext) {
        try{
            driver = DriverFactory.getInstance().getDriver();
         } catch(Exception e ) {
             quitDriver();
             Assert.fail("SetUp failed.", e);
         }
    }


    @AfterClass
    public void quitDriver() {
        try{
            if(driver != null)
                driver.quit();
        }   finally {
            driver = null;
        }
    }

}

Demo程序

public class BaiduMainBaseTest extends TestBase {

    BaiduMainPage page = null;

    @BeforeMethod
    public void initPage() {
        String path = "http://www.baidu.com/";
        page = new BaiduMainPage(driver);
        page.openAndWait(path);
        PageFactory.initElements(driver, page);
    }

    @Test
    public void testSearch(){
        String text="apple";
        page.SearchText(text);
        sleep(1);
        System.out.println(driver.getTitle());
        Assert.assertTrue(driver.getTitle().contains(text));
        System.out.println(page.getCurrentUrl());
    }

    @Test
    public void testnews(){
        System.out.println(page.getCurrentUrl());

        page.clickNewsIndex();
        page.sleep(1);
        System.out.println(page.getCurrentUrl());
        Assert.assertTrue(page.getCurrentUrl().contains("news.baidu.com"));
    }

}

Page增加等待

/**
 * 加载页面,并等待加载完成。
 * @param url
 */
public void openAndWait(String url) {
    Selenium selenium = new WebDriverBackedSelenium(driver,url);
    driver.get(url);
    selenium.waitForPageToLoad("5000");
}

你可能感兴趣的:(java,selenium,测试框架)