在BaiduSearchStepfs.java 文件中,我们可看到都是直接用driver对页面进行操作。对于我们刚开始学习来说,这样没问题。但是随着项目的运行,页面多了以后。我们写的用例也多了以后,当开发改变某个页面元素后,那我们需要修改代码的工作量将是非常多。所以如果我们能够用Page模式来管理各个页面,那后面页面元素有改变的话,我们只需要改下具体某个页面的Eelement就可以了
1、创建一个类来启动driver
写一个类,用于启动并设置driver各个属性等
在目录test的子目录cucumber下新建utl目录,并在该目录下新建一个类SharedDriver.java
在类SharedDriver.java输入下面内容:
import com.cucumber.config.ConfigManager;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
public class SharedDriver extends EventFiringWebDriver {
private static WebDriver REAL_DRIVER = null;
private static final Thread CLOSE_THREAD = new Thread() {
@Override
public void run() {
REAL_DRIVER.close();
}
};
static {
Runtime.getRuntime().addShutdownHook(CLOSE_THREAD);
ConfigManager config = new ConfigManager();
DesiredCapabilities browser = null;
if ("firefox".equalsIgnoreCase(config.get("browser"))) {
browser = DesiredCapabilities.firefox();
} else {
browser = DesiredCapabilities.chrome();
}
browser.setJavascriptEnabled(true);
try {
REAL_DRIVER = new RemoteWebDriver(new URL(config.get("selenium_server_url")), browser);
} catch (MalformedURLException exceptions) {
}
}
public SharedDriver () {
super(REAL_DRIVER);
REAL_DRIVER.manage().window().maximize();
REAL_DRIVER.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
@Override
public void close() {
if (Thread.currentThread() != CLOSE_THREAD) {
throw new UnsupportedOperationException("You shouldn't close this WebDriver. It's shared and will close when the JVM exits.");
}
super.close();
}
@Before
public void deleteAllCookies() {
REAL_DRIVER.manage().deleteAllCookies();
}
@After
public void embedScreenshot(Scenario scenario) {
try {
byte[] screenshot = getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshot, "image/png");
} catch (WebDriverException somePlatformsDontSupportScreenshots) {
System.err.println(somePlatformsDontSupportScreenshots.getMessage());
}
}
}
上面代码要引用另外一个类ConfigManager.java ,该类用来查找一些配置等
在目录test的子目录cucumber下新建config目录,并在该目录下新建一个类ConfigManager.java
在类ConfigManager.java输入下面内容:
public class ConfigManager {
private static Properties defaultProperties = null;
static {
defaultProperties = new Properties();
try {
defaultProperties.load(new FileReader("config/default.properties"));
File customConfigFile = new File("config/custom.properties");
if (customConfigFile.exists()) {
defaultProperties.load(new FileReader(customConfigFile));
}
} catch (IOException exception) {
System.err.println("未找到配置文件");
}
if (!defaultProperties.isEmpty()) {
for (Object key : defaultProperties.keySet()) {
if (System.getProperty((String)key) != null) {
defaultProperties.setProperty((String)key, System.getProperty((String)key));
}
}
}
}
public ConfigManager() {
}
public String get(String key) {
return defaultProperties.getProperty(key);
}
}
之后在项目下,新建目录config,并创建两个文件custom.properties(自己用的配置文件,可以随意修改) 和 default.properties(可以留作后面团队整体运行测试时用)
两个文件的内容可以一样,如下所示
selenium_server_url = http://127.0.0.1:4444/wd/hub
browser = chrome
base_path = http://www.baidu.com
2、创建一个Page来封装百度首页
在目录main下新建一个目录com, 并在该目录下新建一个类BaiduHome_page.java。该类用来封装百度首页
在类BaiduHome_page.java输入下面内容:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class BaiduHome_page {
public WebDriver driver;
public BaiduHome_page(WebDriver driver){
this.driver = driver;
PageFactory.initElements(driver, this);
}
//百度logo
@FindBy(xpath="//div[@id='lg']/img")
public WebElement ElementBaiduLogo;
//输入框
@FindBy(id="kw")
public WebElement ElementBaiduInput;
//按钮 查询一下
@FindBy(id="su")
public WebElement ElementSubmit;
//获取当前页面面包屑信息 预约订单
public String getPageTitle(){
return driver.getTitle();
}
// 输入查询内容,并点击查询按钮
public void enterSearch(String searchText){
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.elementToBeClickable(ElementBaiduInput));
ElementBaiduInput.clear();
ElementBaiduInput.sendKeys(searchText);
ElementSubmit.click();
}
// 输入查询内容,并点击查询按钮
public void submit(){
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.elementToBeClickable(ElementSubmit));
ElementSubmit.click();
}
}
3、修改类BaiduSearchStepfs.java
修改类BaiduSearchStepfs.java,内容如下所示:
import com.BaiduHome_page;
import com.cucumber.config.ConfigManager;
import com.cucumber.utl.SharedDriver;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
public class BaiduSearchStepfs {
private final WebDriver driver;
private final ConfigManager config;
private final BaiduHome_page baiduHome_page;
private static String baseUrl;
public BaiduSearchStepfs(SharedDriver driver, ConfigManager config, BaiduHome_page baiduHome_page) {
this.driver = driver;
this.config = config;
this.baiduHome_page = baiduHome_page;
}
@Given("^Go to baidu home$")
public void go_to_baidu_home() throws Exception {
baseUrl = this.config.get("base_path");
this.driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
this.driver.manage().timeouts().setScriptTimeout(60, TimeUnit.SECONDS);
this.driver.navigate().to(baseUrl);
}
@When("^I find baidu logo")
public WebElement i_find_baidu_logo() {
WebElement element = this.baiduHome_page.ElementBaiduLogo;
return element;
}
@And("^Type the search text \"([^\"]*)\"$")
public void type_the_search_text(String searchText) throws Throwable {
this.baiduHome_page.enterSearch(searchText);
}
@And("^Click the submit$")
public void click_the_submit() {
this.baiduHome_page.submit();
}
@Then("^Wait the query result")
public void wait_the_query_result() throws InterruptedException {
Thread.sleep(10000); //后面可以用显示等待或者隐示等待来优化代码
Assert.assertEquals("selenium_百度搜索", this.baiduHome_page.getPageTitle());
}
}
4、运行程序
注意:上面我们是使用RemoteWebDriver,所以需要启动Selenium Standalone Server服务
到官网http://www.seleniumhq.org/download/,下载Selenium Standalone Server,并下载chromedriver.exe,放到指定的目录
通过命令行形式启动 Remote Webdriver服务器端
java -Dwebdriver.chrome.driver=chromedriver.exe –jar selenium-server-standalone-2.53.0.jar
上述命令需要注意文件路径要写对,并可保存到start.bat文件中,以后每次双击即可启动Remote Webdriver服务器端
然后运行程序,运行结束后查看日志,一切正常,如下图所示