selenium之终极封装

来源:互联网 发布:手机淘宝没有评价订单 编辑:程序博客网 时间:2024/06/06 17:29

目录结构:

这里写图片描述
这里写图片描述

base包:

DriverBase类:

package com.selenium.wushuaiTest.base;import java.io.File;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.Date;import java.util.List;import java.util.Set;import org.apache.commons.io.FileUtils;import org.openqa.selenium.By;import org.openqa.selenium.Cookie;import org.openqa.selenium.OutputType;import org.openqa.selenium.TakesScreenshot;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.interactions.Actions;import com.selenium.wushuaiTest.page.LoginPage;//浏览器的基类public class DriverBase {    public WebDriver driver;    //构造方法    public DriverBase(String browser) {        //初始化浏览器选择类        SelectDriver selectDriver=new SelectDriver();        //把确定之后的浏览器实例赋值给当前的Webdriver        this.driver=selectDriver.driverName(browser);    }    /*     * 获取driver     * */    public WebDriver getDriver() {        return driver;    }    //关闭浏览器驱动方法    public void stopDriver() {        System.out.println("Stop Driver!");        driver.close();    }    /*     * 封装Element方法     *      * */    public WebElement findElement(By by) {        WebElement element=driver.findElement(by);        return element;    }    /*     * get封装     * */    public void get(String url) {        driver.get(url);    }    /*     * 封装click(点击)方法     * 需要传入一个WebElement类型的元素     *      * */    public void click(WebElement element) {        if(element!=null) {            element.click();        }else {            System.out.println("元素未定位到,定位失败");        }    }    /*     * 返回     *      * */    public void back() {        driver.navigate().back();    }    /*     * 刷新     *      * */    public void refresh() {        driver.navigate().refresh();;    }    /**     * 屏幕最大化     *      * */    public void getWindowMax() {        driver.manage().window().maximize();    }    /*     * 休眠     * */    public void sleep(int num) {        try {            Thread.sleep(num);        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    /**     * 切换alert窗口     *      * */    public void switchAlert() {        driver.switchTo().alert();    }    /**     *      * 模态框切换     * */    public void switchToMode() {        driver.switchTo().activeElement();    }     /**     * actionMoveElement     * */    public void action(WebElement element){        Actions action =new Actions(driver);        action.moveToElement(element).perform();    }    /**     * 获取cookcie     * @return      * */    public Set<Cookie> getCookie(){        Set<Cookie> cookies = driver.manage().getCookies();        return cookies;    }    /**     * 删除cookie     * */    public void deleteCookie(){        driver.manage().deleteAllCookies();    }    /**     * 设置cookie     * */    public void setCookie(Cookie cookie){        driver.manage().addCookie(cookie);    }    /**     * 获取当前系统窗口list     * */    public List<String> getWindowsHandles(){        Set<String> winHandels = driver.getWindowHandles();        List<String> handles = new ArrayList<String>(winHandels);        return handles;    }    /*     * 获取当前窗口     * **/    public String getWindowHandle(){        return driver.getWindowHandle();    }    /**     * 切换windows窗口     * */    public void switchWindows(String name){        driver.switchTo().window(name);    }    /**     * 获取当前url     * */    public String getUrl(){        return driver.getCurrentUrl();    }    /**     * 获取title     * */    public String getTitle(){        return driver.getTitle();    }    /**     * 传入参数截图     * */    public void takeScreenShot(TakesScreenshot drivername, String path) {        String currentPath = System.getProperty("user.dir"); // get current work        File scrFile = drivername.getScreenshotAs(OutputType.FILE);        try {            FileUtils.copyFile(scrFile, new File(currentPath + "\\" + path));        } catch (Exception e) {            e.printStackTrace();        } finally {            System.out.println("截图成功");        }    }      /**     * 封装定位一组elements的方法     * */    public List<WebElement> findElements(By by){        return driver.findElements(by);    }    /**     * 自动截图     * */    public void takeScreenShot() {        SimpleDateFormat sf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");        Calendar cal = Calendar.getInstance();        Date date = cal.getTime();        String dateStr = sf.format(date);        String path = this.getClass().getSimpleName() + "_" + dateStr + ".png";        takeScreenShot((TakesScreenshot) this.getDriver(), path);        //takeScreenShot((TakesScreenshot) driver, path);    }}

SelectDriver类:

package com.selenium.wushuaiTest.base;import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.firefox.FirefoxDriver;//选择浏览器类型的类public class SelectDriver {    public WebDriver driverName(String browser) {        //equalsIgnoreCase代表不区分大小写        //判断浏览器的类型是"firefox"或者"chrome"又或者是"IE"        if(browser.equalsIgnoreCase("fireFox"))        {            System.setProperty("webdriver.firefox.marionette", "D:\\\\java\\\\geckodriver\\\\geckodriver.exe");            return new FirefoxDriver();        }else{            System.setProperty("webdriver.chrome.driver","D:\\\\java\\\\chromedriver-32\\\\chromedriver.exe");            return new ChromeDriver();        }    }}

business包:

CoursePagePro类:

package com.selenium.wushuaiTest.business;import java.util.List;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.handle.CoursePageHandle;public class CoursePagePro {    public DriverBase driver;    public CoursePageHandle coursePageHandle;    public CoursePagePro(DriverBase driver) {        this.driver=driver;        coursePageHandle=new CoursePageHandle(driver);    }    /**     *      * 添加购物车     * */    public void addCart() {        int beforeNum;        String afterCourseNum;        int afterNum;        //在没点击加入购物车按钮前,先获得购物车商品的数量        String courseNum=coursePageHandle.getShopCartNum();        try {            beforeNum=Integer.valueOf(courseNum);            System.out.println(beforeNum);        }catch(Exception e){            beforeNum=0;        }        //点击加入购物车        coursePageHandle.clickAddCart();        try {            //转接模态框            driver.switchToMode();            //点击“立即购买”按钮            coursePageHandle.clickBuyNow();        } catch (Exception e) {            // TODO: handle exception        }        // 得到购物车商品的数量        afterCourseNum = coursePageHandle.getShopCartNum();        try {            afterNum=Integer.valueOf(afterCourseNum);            System.out.println(afterNum);        } catch (Exception e) {            afterNum=beforeNum;        }        driver.sleep(2000);        if(afterNum==beforeNum+1) {            System.out.println("添加购物车成功!");            //点击右上角的购物车按钮            coursePageHandle.clickShopCart();            driver.sleep(2000);            //点击去结算按钮            coursePageHandle.clickGoPay();        }else if(afterNum>0) {            //点击右上角的购物车按钮            coursePageHandle.clickShopCart();            driver.sleep(2000);            //点击去结算按钮            coursePageHandle.clickGoPay();        }else {            //点击右上角的购物车按钮            coursePageHandle.clickShopCart();            driver.sleep(5000);            List<String> list=driver.getWindowsHandles();            driver.switchWindows(list.get(1));            System.out.println(driver.getTitle());            coursePageHandle.clickGoPay();        }    }    /**     * 点击立即购买按钮     *      * */    public void buyNow() {        coursePageHandle.clickBuyNow();    }}

HomePagePro类:

package com.selenium.wushuaiTest.business;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.handle.HomePageHandle;public class HomePagePro {    public HomePageHandle hph;    public HomePagePro(DriverBase driver){        hph =new HomePageHandle(driver);    }    /**     * 点击登陆按钮     * */    public void clickLoginButton(){        hph.clickLogin();    }    /**     * 点击实战按钮     * */    public void clickCodingLink(){        hph.clickCoding();    }    /**     * 根据用户名判断登陆信息是否正确     * */    public Boolean AssertLogin(String username){        if(hph.getUserName().equals(username)){            return true;        }        return false;    }}

LoginPro类:

package com.selenium.wushuaiTest.business;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.handle.LoginPageHandle;public class LoginPro {    public LoginPageHandle loginPageHandle;    public LoginPro(DriverBase driverBase) {        loginPageHandle=new LoginPageHandle(driverBase);    }    public void login(String userName,String password) {        //如果能够识别用户名输入框,那么就代表登录页面存在,就可以进行输入用户名,密码等操作        if(loginPageHandle.assertLoginPage()) {            //输入用户名            loginPageHandle.sendKeysUserName(userName);            //输入密码            loginPageHandle.sendKeysPassword(password);            //点击自动登录            loginPageHandle.clickAutoSigin();            //点击登录            loginPageHandle.clickLoginButton();        }else {            System.out.println("页面不存在或者状态不正确");        }    }}

OrderPayPro类:

package com.selenium.wushuaiTest.business;import org.openqa.selenium.JavascriptExecutor;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.handle.OrderPayHandle;public class OrderPayPro {    public DriverBase driverBase;    public OrderPayHandle orderPayHandle;    public OrderPayPro(DriverBase driverBase) {        this.driverBase=driverBase;        orderPayHandle=new OrderPayHandle(driverBase);    }    /**     * 根据课程信息与订单是否正确判断是否跳转到支付页面     *      * */    public void orderPayPro() {        String orderName=orderPayHandle.getOrderName();        String orderCourseName=orderPayHandle.getOrderCourseName();        if(orderName!=null&&orderCourseName!=null) {            //选中支付宝支付            orderPayHandle.clickAliPay();            //点击立即支付            JavascriptExecutor js = (JavascriptExecutor) driverBase.getDriver();            js.executeScript("arguments[0].click();",orderPayHandle.orderPayPage.getOrderPayElement());            //orderPayHandle.clickPayElement();        }    }}

SureOrderPro类:

package com.selenium.wushuaiTest.business;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.handle.SureOrderPageHandle;public class SureOrderPro {    public SureOrderPageHandle sureOrderPageHandle;    public DriverBase driverBase;    public SureOrderPro(DriverBase driverBase) {        this.driverBase=driverBase;        sureOrderPageHandle=new SureOrderPageHandle(driverBase);    }    /**     * 点击提交订单按钮     *      * */    public void sureOrder() {        sureOrderPageHandle.clickSureOrderButton();    }}

handle包:

CoursePageHandle类:

package com.selenium.wushuaiTest.handle;import org.openqa.selenium.WebElement;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.page.CoursePage;public class CoursePageHandle {    private DriverBase driver;    private CoursePage coursePage;    public CoursePageHandle(DriverBase driver) {        // TODO Auto-generated constructor stub        this.driver=driver;        coursePage=new CoursePage(driver);    }    /**     * 点击立即购买按钮     *      * */    public void clickBuyNow() {        coursePage.click(coursePage.getPurchaseNowElement());    }    /**     * 点击添加购物车按钮     *      * */    public void clickAddCart() {        coursePage.click(coursePage.getAddCartElement());    }    /**     *      * 点击右上角购物车     * */    public void clickShopCart() {        coursePage.click(coursePage.getShopCartElement());    }    /**     *      * 获取购物车数量     * */    public String getShopCartNum() {        WebElement element=coursePage.getShopCartNumElement();        return coursePage.getText(element);    }    /**     * 获取课程名称     *      * */    public String getCourseName() {            return coursePage.getText(coursePage.getCourseNameElement());    }    /**     *      * 点击已经购买弹窗的确定按钮     * */    public void clickReadBuy() {        coursePage.click(coursePage.getReadyBuy());    }    /**     * 去结算     * */    public void clickGoPay(){        coursePage.click(coursePage.getGoPayElement());    }}

HomePageHandle类:

package com.selenium.wushuaiTest.handle;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.page.HomePage;public class HomePageHandle {    public DriverBase driver;    public HomePage hp;    public HomePageHandle(DriverBase driver){        this.driver = driver;        hp = new HomePage(driver);    }    /**     * 点击登陆按钮     * */    public void clickLogin(){        hp.click(hp.getLoginElement());    }    /**     * 点击实战按钮     * */    public void clickCoding(){        hp.click(hp.getCodingElement());    }    /**     * 获取用户名     * */    public String getUserName(){        String username = hp.getText(hp.getUserNameElement());        return username;    }}

LoginPageHandle类:

package com.selenium.wushuaiTest.handle;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.page.LoginPage;public class LoginPageHandle {    public DriverBase driverBase;    // 由于是操作的登录,所以要实例化LoginPage    public LoginPage loginPage;    public LoginPageHandle(DriverBase driverBase) {        this.driverBase=driverBase;        loginPage=new LoginPage(driverBase);    }    /*     * 输入用户名     * */    public void sendKeysUserName(String userName) {        loginPage.sendKeys(loginPage.getUserElement(), userName);    }    /*     * 输入密码     * */    public void sendKeysPassword(String password) {        loginPage.sendKeys(loginPage.getPasswordElement(),password);    }    /*     * 点击登录     *      * */    public void clickLoginButton() {        loginPage.click(loginPage.getLoginButtonElement());    }    /*     * 点击自动登录     *      * */    public void clickAutoSigin() {        loginPage.click(loginPage.getAutoLoginElement());    }    /*     * 判断是否是登录页面     * 判断标准:只要能够识别登录页面的一个输入框即可,这里使用用户名来识别     *      * */    public boolean assertLoginPage() {        return loginPage.assertElementIs(loginPage.getUserElement());    }}

OrderPayHandle类:

package com.selenium.wushuaiTest.handle;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.page.OrderPayPage;public class OrderPayHandle {    public DriverBase driverBase;    public OrderPayPage orderPayPage;    public OrderPayHandle(DriverBase driverBase) {        this.driverBase=driverBase;        orderPayPage=new OrderPayPage(driverBase);    }    /**     * 获取订单文字     *      * */    public String getOrderName() {        return orderPayPage.getText(orderPayPage.getOrderNumElement());    }    /**     * 获取课程名称     *      * */    public String getOrderCourseName() {        return orderPayPage.getText(orderPayPage.getOrderCoureNameElement());    }    /**     * 点击支付宝支付     *      * */    public void clickAliPay() {        orderPayPage.click(orderPayPage.getAliPayElement());    }    /**     * 点击立即支付     *      * */    public void clickPayElement() {        orderPayPage.click(orderPayPage.getOrderPayElement());    }}

SureOrderPageHandle类:

package com.selenium.wushuaiTest.handle;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.page.SureOrderPage;public class SureOrderPageHandle {        public DriverBase driverBase;        public SureOrderPage sureOrderPage;        public SureOrderPageHandle(DriverBase driverBase) {            this.driverBase=driverBase;            sureOrderPage=new SureOrderPage(driverBase);        }        /**         * 点击"提交订单按钮"         *          * */        public void clickSureOrderButton() {            driverBase.click(sureOrderPage.getSureOrderButton());        }}

page包:

基类-BasePage

package com.selenium.wushuaiTest.page;import java.util.List;import org.openqa.selenium.By;import org.openqa.selenium.NoSuchWindowException;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.util.GetByLocator;//基本页面的类public class BasePage {    public DriverBase driver;    //构造方法    public BasePage(DriverBase driver) {        //把初始化传入的DriverBase赋值给当前BasePage类的DriverBase的变量        this.driver=driver;    }    /*     * 定位Element     *      * @param By by     *      * */    public WebElement element(By by) {        WebElement ele=driver.findElement(by);        return ele;    }    /*     * 封装click(点击)方法     * 需要传入一个WebElement类型的元素     *      * */    public void click(WebElement element) {        if(element!=null) {            element.click();        }else {            System.out.println("元素未定位到,定位失败");        }    }    /*     * 封装输入方法     *      * */    public void sendKeys(WebElement element,String value) {        if(element!=null) {            element.sendKeys(value);        }else {            System.out.println(element+"元素没有定位到,输入失败"+value);        }    }    /*     * 判断元素是否显示方法     *      * */    public boolean assertElementIs(WebElement element) {        return element.isDisplayed();    }    /**     * 层级定位,通过父节点定位到子节点     * 需要传入父节点和子节点的By     * */    public WebElement getChildrenElement(By parentBy,By childrenBy) {        WebElement ele=this.element(parentBy);        return ele.findElement(childrenBy);    }    /**     * 层级定位传入element,以及子的by     *     * */    public WebElement getChildrenElement(WebElement element,By by){        return element.findElement(by);    }    /**     * 定位一组elements     * */    public List<WebElement> elements(By by){        return driver.findElements(by);    }    /**     * 通过父节点定位一组elements     * */    public List<WebElement> elements(WebElement element,By by){        return element.findElements(by);    }    /*     * 获取文本信息     *      * */    public String getText(WebElement element) {        return element.getText();    }     /**     * action事件     * */    public void action(WebElement element){        driver.action(element);    }    /**     * 获取title     * */    public String getTitle(){        return driver.getDriver().getTitle();    }    /**     * 关闭浏览器     * */    public void close(){        driver.getDriver().close();    }    /**     * 获取当前窗口所有的windows     * */    public List<String> getWindowsHandles(){        List<String> handles = driver.getWindowsHandles();        return handles;    }    /**     * 根据title切换新窗口     * */    public boolean switchToWindow_Title(String windowTitle) {        boolean flag = false;        try {            String currentHandle = driver.getWindowHandle();            List<String> handles = driver.getWindowsHandles();            for (String s : handles) {                if (s.equals(currentHandle))                    continue;                else {                    driver.switchWindows(s);                    if (driver.getDriver().getTitle().contains(windowTitle)) {                        flag = true;                        System.out.println("切换windows成功: " + windowTitle);                        break;                    } else                        continue;                }            }        } catch (NoSuchWindowException e) {            System.out.println("Window: " + windowTitle + " 没找到!!!"                    + e.fillInStackTrace());            flag = false;        }        return flag;    }}

CoursePage类:

package com.selenium.wushuaiTest.page;import org.openqa.selenium.WebElement;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.util.GetByLocator;public class CoursePage extends BasePage{    public CoursePage(DriverBase driverBase) {        super(driverBase);        // TODO Auto-generated constructor stub    }    /*     * 获取"立即购买"按钮element     *      * */    public WebElement getPurchaseNowElement() {        return element(GetByLocator.getLocator("purchaseNow"));    }    /**     * 获取添加购物车element     *      * */    public WebElement getAddCartElement() {        return element(GetByLocator.getLocator("addCart"));    }    /**     * 获取右上角购物车element     *      * */    public WebElement getShopCartElement() {        return element(GetByLocator.getLocator("shopCart"));    }    /**     * 获取购物车数量element     *      * */    public WebElement getShopCartNumElement() {        return element(GetByLocator.getLocator("cartNum"));    }    /**     * 获取课程详情页面左上角课程名element     *      * */    public WebElement getCourseNameElement() {        return getChildrenElement(GetByLocator.getLocator("courseInfo"), GetByLocator.getLocator("courseInfoText"));    }    /**     * 通过字符节点定位已经购买弹窗确定按钮     *      * */    public WebElement getReadyBuy() {        return getChildrenElement(GetByLocator.getLocator("readBuySure"), GetByLocator.getLocator("readBuySureNode"));    }    /**     * 购物车页面去结算     * */    public WebElement getGoPayElement(){        return getChildrenElement(GetByLocator.getLocator("shopgopay"),GetByLocator.getLocator("shopgopayNode"));    }}

HomePage类:

package com.selenium.wushuaiTest.page;import org.openqa.selenium.WebElement;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.util.GetByLocator;public class HomePage extends BasePage{    public HomePage(DriverBase driver){        super(driver);    }    /**     * 获取点击登陆element     * */    public WebElement getLoginElement(){        return element(GetByLocator.getLocator("login"));    }    /**     * 获取实战element     * */    public WebElement getCodingElement(){        return getChildrenElement(GetByLocator.getLocator("tophead"),GetByLocator.getLocator("coding"));    }    /**     * 获取用户名信息element     * */    public WebElement getUserNameElement(){        action(element(GetByLocator.getLocator("header")));        return element(GetByLocator.getLocator("nameInfo"));    }}

LoginPage类:

package com.selenium.wushuaiTest.page;import org.openqa.selenium.WebElement;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.util.GetByLocator;public class LoginPage extends BasePage{    public LoginPage(DriverBase driverBase) {        super(driverBase);        // TODO Auto-generated constructor stub    }    /*     * 获取用户名输入框Element     *      * */    public WebElement getUserElement() {        //找到properties中的userName变量        return element(GetByLocator.getLocator("userName"));    }    /*     * 获取密码输入框Element     *      * */    public WebElement getPasswordElement() {        return element(GetByLocator.getLocator("userPass"));    }    /*     * 获取登录按钮输入框     *      * */    public WebElement getLoginButtonElement() {        return element(GetByLocator.getLocator("buttonElement"));    }    /*     * 获取自动登录Element     *      * */    public WebElement getAutoLoginElement() {        return element(GetByLocator.getLocator("autoSigin"));    }}

OrderPayPage类:

package com.selenium.wushuaiTest.page;import org.openqa.selenium.WebElement;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.util.GetByLocator;public class OrderPayPage extends BasePage{    public OrderPayPage(DriverBase driverBase) {        super(driverBase);        // TODO Auto-generated constructor stub    }    /**     *      * 获取订单号element     * */    public WebElement getOrderNumElement() {        return element(GetByLocator.getLocator("orderNum"));    }    /**     * 返回课程名称element     *      * */    public WebElement getOrderCoureNameElement() {        return element(GetByLocator.getLocator("orderCourseNode"));    }    /**     * 返回支付宝element     *      * */    public WebElement getAliPayElement() {        return element(GetByLocator.getLocator("alipay"));    }    /**     * 获取"立即支付"element     *      * */    public WebElement getOrderPayElement() {        return element(GetByLocator.getLocator("orderPay"));    }}

SureOrderPage类:

package com.selenium.wushuaiTest.page;import org.openqa.selenium.WebElement;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.util.GetByLocator;public class SureOrderPage extends BasePage{    public SureOrderPage(DriverBase driverBase) {        super(driverBase);        // TODO Auto-generated constructor stub    }    /**     * 获取提交订单按钮     *      * */    public WebElement getSureOrderButton() {        return element(GetByLocator.getLocator("sureOrder"));    }}

testCase包:

基类-CaseBase

package com.selenium.wushuaiTest.testCase;//初始化浏览器import com.selenium.wushuaiTest.base.DriverBase;public class CaseBase {    public DriverBase InitDriverBase(String browser) {        return new DriverBase(browser);    }}

Login类:

package com.selenium.wushuaiTest.testCase;import org.apache.log4j.Logger;import org.openqa.selenium.By;import org.openqa.selenium.WebElement;import org.testng.Assert;import org.testng.annotations.AfterClass;import org.testng.annotations.BeforeClass;import org.testng.annotations.Parameters;import org.testng.annotations.Test;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.business.CoursePagePro;import com.selenium.wushuaiTest.business.LoginPro;import com.selenium.wushuaiTest.business.OrderPayPro;import com.selenium.wushuaiTest.business.SureOrderPro;import com.selenium.wushuaiTest.util.GetByLocator;public class Login extends CaseBase{    public DriverBase driverBase;    public LoginPro loginPro;    public CoursePagePro coursePagePro;    public SureOrderPro sureOrderPro;    public OrderPayPro orderPayPro;    //使用静态声明主要是为了在第一次进来的时候就调用生成,并且有且仅有一次    //static Logger logger=Logger.getLogger(Login.class);    //@BeforeClass代表在运行第一个@Test之前执行这个方法    @BeforeClass    public void loginTest() {        //确定运行脚本的为chrome浏览器,并且赋值给当前类的DriverBase        this.driverBase=InitDriverBase("chrome");        loginPro=new LoginPro(driverBase);        coursePagePro=new CoursePagePro(driverBase);        sureOrderPro=new SureOrderPro(driverBase);        orderPayPro=new OrderPayPro(driverBase);    }    @Test    public void getLoginHome() {        driverBase.get("http://www.imooc.com");        driverBase.getWindowMax();        driverBase.findElement(By.id("js-signin-btn")).click();        //driverBase.findElement(GetByLocator.getLocator("loginButton")).click();           driverBase.sleep(2000);    }    @Test(dependsOnMethods={"getLoginHome"})    @Parameters({"username","password"})    public void testLogin(String username,String password) {        //logger.debug("的空间里的封建时代放疗科大夫——————————————————————————————————————————————————————");        loginPro.login(username,password);    }    /**     * 添加购物车     *      * */    @Test(dependsOnMethods={"testLogin"})    public void addCart() {        driverBase.sleep(2000);        driverBase.get("http://coding.imooc.com/class/147.html");        coursePagePro.addCart();    }    /**     * 提交订单     *      * */    @Test(dependsOnMethods={"addCart"})    public void TestSureOrder() {        sureOrderPro.sureOrder();    }    /**     * 跳转支付页面进行支付     *      * */    @Test(dependsOnMethods={"TestSureOrder"})    public void testGoBuy() {        driverBase.sleep(2000);        orderPayPro.orderPayPro();    }    @AfterClass    public void closeDriver() {        driverBase.getDriver().close();    }}

SuiteTestBuy类:

package com.selenium.wushuaiTest.testCase;import org.testng.annotations.AfterClass;import org.testng.annotations.BeforeClass;import org.testng.annotations.Test;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.business.CoursePagePro;import com.selenium.wushuaiTest.util.HandleCookie;public class SuiteTestBuy extends CaseBase{    public DriverBase driverBase;    public CoursePagePro coursePagePro;    public HandleCookie handleCookie;    @BeforeClass    public void beforeClass() {        this.driverBase=InitDriverBase("chrome");        coursePagePro=new CoursePagePro(driverBase);        //为了得到我们添加到Set集合中的cookie,所以我们需要得到handlecookie对象        handleCookie=new HandleCookie(driverBase);        /**         *          *易错点:先执行handleCookie.setCookie();         *再进入网页driverBase.get("http://coding.imooc.com/class/149.html");         * 错误原因:典型的执果索因,如果我们提前设置cookie,猛一看上去没毛病,         * 但仔细一想,你都不知道进哪个网页,你把cookie设置给谁呢?我们的大前提弄错了         *          * driverBase.get("http://coding.imooc.com/class/149.html");         * handleCookie.setCookie();         * 进入页面后紧接着设置完cookie后,网页不会自动刷新,所以我们要自己重新加载一下网页         *          * */        //直接进入到课程页面        driverBase.get("http://coding.imooc.com/class/149.html");        //指定用户的cookie,相当于指定了谁登陆        handleCookie.setCookie();        //设定完Cookie后,必须重新加载一下页面,否则会失败        driverBase.get("http://coding.imooc.com/class/149.html");    }    @Test    public void testBuy() {        //执行立即购买        coursePagePro.buyNow();        //driverBase.sleep(2000);    }    @AfterClass    public void afterClass() {        //driverBase.getDriver().close();    }}

SuiteTestLogin类:

package com.selenium.wushuaiTest.testCase;import java.util.concurrent.TimeUnit;import org.openqa.selenium.Cookie;import org.testng.annotations.AfterClass;import org.testng.annotations.BeforeClass;import org.testng.annotations.Parameters;import org.testng.annotations.Test;import com.selenium.wushuaiTest.base.DriverBase;import com.selenium.wushuaiTest.business.HomePagePro;import com.selenium.wushuaiTest.business.LoginPro;import com.selenium.wushuaiTest.util.HandleCookie;import com.selenium.wushuaiTest.util.ProUtil;public class SuiteTestLogin extends CaseBase{    public DriverBase driver;    public LoginPro loginPro;    public ProUtil proUtil;    public HomePagePro homePagePro;    public HandleCookie handleCookie;    //相当于构造方法    @BeforeClass    public void beforeClass() {        this.driver=InitDriverBase("chrome");        proUtil=new ProUtil("loginTest.properties");        handleCookie=new HandleCookie(driver);        //设置系统响应时间为10秒钟        driver.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);        loginPro=new LoginPro(driver);        homePagePro=new HomePagePro(driver);        driver.get(proUtil.getPro("url"));        driver.getWindowMax();    }    @Test    @Parameters({"username","password"})    public void testLogin(String username,String password) {        loginPro.login(username, password);        driver.sleep(5000);        if(homePagePro.AssertLogin(proUtil.getPro("yq"))){            System.out.println("登陆成功"+username);            //确定登录成功后,写入我们当前用户的Cookie            handleCookie.writeCookie();        }    }    @AfterClass    public void afterClass() {        driver.getDriver().close();    }}

TestCourseList类:

package com.selenium.wushuaiTest.testCase;import java.util.ArrayList;import java.util.List;import org.openqa.selenium.By;import org.openqa.selenium.JavascriptExecutor;import org.openqa.selenium.WebElement;import org.testng.annotations.Test;import com.selenium.wushuaiTest.base.DriverBase;public class TestCourseList extends CaseBase{    public DriverBase driver;    public TestCourseList() {        this.driver=InitDriverBase("chrome");    }    @Test    public void CourseList(){        driver.get("http://coding.imooc.com/");        List<String> listString = this.listElement();        for(int i=0;i<listString.size();i++){            //driver.findElement(By.xpath("//*[contains(text(),'"+listString.get(i)+"')]")).click();//          用selenium模拟用户单击元素时,JS有一个操作鼠标悬浮的时候会对元素进行修改//          解决办法:用JS来操作元素            //点击关键文本下的课程用js操作,如果直接用//driver.findElement(By.xpath("//*[contains(text(),'"+listString.get(i)+"')]")).click();            //会报错,因为用selenium模拟用户单击元素时,JS有一个操作鼠标悬浮的时候会对元素进行修改//          解决办法:用JS来操作元素            JavascriptExecutor js = (JavascriptExecutor) driver.getDriver();            js.executeScript("arguments[0].click();",driver.findElement(By.xpath("//*[contains(text(),'"+listString.get(i)+"')]")));            driver.back();        }    }    /*     * 获取所有的课程List     *      * */    public List<String> listElement(){        List<String> listString=new ArrayList<String>();        // 拿到实战中的列表集合元素        WebElement element = driver.findElement(By.className("shizhan-course-list"));        // 拿到实战课程的元素的集合        List<WebElement> courseList = element.findElements(By.className("shizhan-intro-box"));        for (WebElement element2 : courseList) {            //得到每个课程的关键信息文本并且放入集合中            listString.add(element2.findElement(By.className("shizan-desc")).getText());            System.out.println(element2.findElement(By.className("shizan-name")).getText());        }        return listString;    }}

util包:

baseDriver类:-这个类可有可无!

package com.selenium.wushuaiTest.util;import java.io.File;import java.io.IOException;import org.apache.commons.io.FileUtils;import org.openqa.selenium.OutputType;import org.openqa.selenium.TakesScreenshot;import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome.ChromeDriver;public class baseDriver {    WebDriver driver;    public baseDriver() {        System.setProperty("webdriver.chrome.driver", "D:\\java\\chromedriver-32\\chromedriver.exe");        driver=new ChromeDriver();        driver.get("http://www.imooc.com");        //窗口最大化        driver.manage().window().maximize();    }    /*     * 截图方法     * */    public void takeScreenShot() {        //获取截图时间        long date=System.currentTimeMillis();        //转换成字符串形式        String path=String.valueOf(date);        String curPath=System.getProperty("user.dir");        path=path+".png";        String screenPath=curPath+"/"+path;        //进行截图操作        File screen=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);        try {            FileUtils.copyFile(screen, new File(screenPath));        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

GetByLocator类:

package com.selenium.wushuaiTest.util;import org.openqa.selenium.By;public class GetByLocator {    public static  By getLocator(String key) {        ProUtil proUtil=new ProUtil("element.properties");        String locator=proUtil.getPro(key);        String locatorType=locator.split(">")[0];        String locatorValue=locator.split(">")[1];        if(locatorType.equals("id"))        {            return By.id(locatorValue);        }else if(locatorType.equals("name"))        {            return By.name(locatorValue);        }else if(locatorType.equals("className"))        {            return By.className(locatorValue);        }else if(locatorType.equals("linkText"))        {            return By.linkText(locatorValue);        }else if(locatorType.equals("tagName")) {            return By.tagName(locatorValue);        }else {            return By.xpath(locatorValue);        }    }}

HandleCookie类:

package com.selenium.wushuaiTest.util;import java.util.Set;import org.openqa.selenium.Cookie;import com.selenium.wushuaiTest.base.DriverBase;public class HandleCookie {    public DriverBase driverBase;    //要读取cookie.properties配置文件,所以需要Proutil工具类    public ProUtil proUtil;    public HandleCookie(DriverBase driverBase) {        this.driverBase=driverBase;        proUtil=new ProUtil("cookie.properties");    }    /**     * 设置cookie方法     *      * */    public void setCookie() {        String value=proUtil.getPro("apsid");        /**         * 五个参数的         * 第一个参数:cookie的名称,任意取         * 第二个参数:cookie的值         * 第三个参数:path:域名地址-代表我们只要是我们所测网站的域名,都表示有效         * 第四个代表全部路径下         * 第五个参数:日期         * */        Cookie cookie=new Cookie("apsid", value, "imooc.com", "/",null);        //把当前的cookie成功添加到Set<Cookie>集合中,在DriverBase类中封装了setCookie方法        driverBase.setCookie(cookie);    }    /**     * 获取cookie方法     * 原理:     *      * */    public void writeCookie() {        Set<Cookie> cookies=driverBase.getCookie();        for(Cookie cookie:cookies) {            if(cookie.getName().equals("apsid")) {                proUtil.writePro(cookie.getName(),cookie.getValue());            }        }    }}

ProUtil类:

package com.selenium.wushuaiTest.util;import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Properties;public class ProUtil {    private Properties prop;    private String filePath;    /*     * 构造方法     * */    //初始化new ProUtil是从外部传回一个properties文件的路径    public ProUtil(String filePath)    {        //外部文件路径赋值给当前类的文件路径        this.filePath=filePath;        this.prop=readProperties();    }    /*     * 读取配置文件     *      * */    private Properties readProperties(){        //创建一个Properties        Properties properties=new Properties();        try {            //使用文件读取并且使用properties文件进行加载出来            InputStream inputStream=new FileInputStream(filePath);            BufferedInputStream bis=new BufferedInputStream(inputStream);            properties.load(bis);        } catch (FileNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return properties;    }    /*     * 封装配置文件中的getProperty方法     * */    public String getPro(String key){        //判断properties文件中是否包含key信息        if(prop.containsKey(key))        {            String username=prop.getProperty(key);            return username;        }else{            System.out.println("你获取的值不存在");            return "";        }    }    /**     * 写入内容     * */    public void writePro(String key,String value){        Properties pro = new Properties();            try {                FileOutputStream file = new FileOutputStream(filePath);                pro.setProperty(key, value);                pro.store(file, key);            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }}

TestngListenerScreenShot类:

package com.selenium.wushuaiTest.util;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.Iterator;import java.util.Set;import org.apache.commons.io.FileUtils;import org.openqa.selenium.OutputType;import org.openqa.selenium.TakesScreenshot;import org.testng.ITestContext;import org.testng.ITestResult;import org.testng.TestListenerAdapter;import com.selenium.wushuaiTest.testCase.Login;public class TestngListenerScreenShot extends TestListenerAdapter{    @Override    public void onTestSuccess(ITestResult tr) {        super.onTestSuccess(tr);    }    @Override    public void onTestFailure(ITestResult tr) {        super.onTestFailure(tr);        System.out.println(tr);        takeScreenShot(tr);    }    private void takeScreenShot(ITestResult tr) {        Login b = (Login) tr.getInstance();        // driver = b.driver;        b.driverBase.takeScreenShot();    }    @Override    public void onTestSkipped(ITestResult tr) {        super.onTestSkipped(tr);    }    @Override    public void onTestStart(ITestResult result) {        super.onTestStart(result);    }    @Override    public void onStart(ITestContext testContext) {        super.onStart(testContext);    }    @Override    public void onFinish(ITestContext testContext) {        super.onFinish(testContext);        ArrayList<ITestResult> testsToBeRemoved = new ArrayList<ITestResult>();        // collect all id's from passed test        Set<Integer> passedTestIds = new HashSet<Integer>();        for (ITestResult passedTest : testContext.getPassedTests()                .getAllResults()) {            //logger.info("PassedTests = " + passedTest.getName());            passedTestIds.add(getId(passedTest));        }        Set<Integer> failedTestIds = new HashSet<Integer>();        for (ITestResult failedTest : testContext.getFailedTests()                .getAllResults()) {            //logger.info("failedTest = " + failedTest.getName());            int failedTestId = getId(failedTest);            // if we saw this test as a failed test before we mark as to be            // deleted            // or delete this failed test if there is at least one passed            // version            if (failedTestIds.contains(failedTestId)                    || passedTestIds.contains(failedTestId)) {                testsToBeRemoved.add(failedTest);            } else {                failedTestIds.add(failedTestId);            }        }        // finally delete all tests that are marked        for (Iterator<ITestResult> iterator = testContext.getFailedTests()                .getAllResults().iterator(); iterator.hasNext();) {            ITestResult testResult = iterator.next();            if (testsToBeRemoved.contains(testResult)) {                //logger.info("Remove repeat Fail Test: " + testResult.getName());                iterator.remove();            }        }    }    private int getId(ITestResult result) {        int id = result.getTestClass().getName().hashCode();        id = id + result.getMethod().getMethodName().hashCode();        id = id                + (result.getParameters() != null ? Arrays.hashCode(result                        .getParameters()) : 0);        return id;    }}

TestngRetry类:

package com.selenium.wushuaiTest.util;import org.testng.IRetryAnalyzer;import org.testng.ITestResult;import org.testng.Reporter;public class TestngRetry implements IRetryAnalyzer{    private static int maxRetryCount = 3;    private int retryCount = 1;    public boolean retry(ITestResult result) {        System.out.println(result);        if (retryCount <= maxRetryCount) {            String message = "Running retry for '" + result.getName()                    + "' on class " + this.getClass().getName() + " Retrying "                    + retryCount + " times";            Reporter.setCurrentTestResult(result);            Reporter.log("RunCount=" + (retryCount + 1));            retryCount++;            return true;        }        return false;    }}

log4j.properties

 ### \u8BBE\u7F6E###log4j.rootLogger = debug,stdout,D,E### \u8F93\u51FA\u4FE1\u606F\u5230\u63A7\u5236\u62AC ###log4j.appender.stdout = org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target = System.outlog4j.appender.stdout.layout = org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n### \u8F93\u51FADEBUG \u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230=E://logs/error.log ###log4j.appender.D = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.D.File = E://logs/log.loglog4j.appender.D.Append = truelog4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayoutlog4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n### \u8F93\u51FAERROR \u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230=E://logs/error.log ###log4j.appender.E = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.E.File =E://logs/error.log log4j.appender.E.Append = truelog4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayoutlog4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

build.xml

<?xml version="1.0" encoding="UTF-8"?><project name= "wushuaiTest" basedir= "." default="transform"><property name= "lib.dir" value= "lib" /><path id= "test.classpath" ><!-- adding the saxon jar to your classpath --><fileset dir= "${lib.dir}" includes= "*.jar" /></path><target name= "transform" ><xslt in= "C:\Users\Administrator\eclipse-workspace\wushuaiTest\test-output/testng-results.xml" style= "C:\Users\Administrator\eclipse-workspace\wushuaiTest\test-output/testng-results.xsl"out= "C:\Users\Administrator\eclipse-workspace\wushuaiTest\test-output/TestReport/index.html " ><!-- you need to specify the directory here again --><param name= "testNgXslt.outputDir" expression= "C:\Users\Administrator\eclipse-workspace\wushuaiTest\test-output/TestReport" /><classpath refid= "test.classpath" /></xslt></target></project>

cookie.properties

key与value根据不同网页而定!

#apsid#Sat Oct 21 19:05:32 CST 2017apsid=A5NjNkOTExZWM3ODVjMTc1Y2ZiZTQ4NjQ4MjZkMzkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANDU2MDY5OAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABtMTMwMzExNTUwNTdAMTYzLmNvbQAAAAAAAAAAAAAAADE2ZDYxZTgwNjY4NDAzMWMwODNlZDZmNWY3YjQzYTU3zynrWc8p61k%3DYT

element.properties

userName=name>emailloginButton=id>js-signin-btnuserPass=name>passwordbuttonElement=className>btn-redheader=id>header-avatornameInfo=className>nameautoSigin=id>auto-signin###courseDetailshopgopay=id>js-cart-body-tableshopgopayNode=className>btnpurchaseNow=id>buy-triggercourseInfo=className>pathcourseInfoText=tagName>spansureOrder=linkText>\u63D0\u4EA4\u8BA2\u5355orderNum=className>orderorderCourse=className>item-leftorderCourseNode=tagName>dtaddCart=className>sz-add-shopping-cartshopCart=id>shop-cartcartNum=className>shopping_iconreadBuy=className>moco-modal-layerreadBuySure=className>moco-modal-innerreadBuySureNode=tagName>span###Alipayalipay=className>alipay###Immediate-paymentorderPay=className>pay-summary-submit#homepage login=id>js-signin-btntophead=className>nav-itemcoding=linkText>\u5B9E\u6218

loginTest.properties

url=http://www.imooc.com/user/newlogin/from_url/username=m13031155057@163.compasswd=1111yq=qq_\u8F6C\u89D2\u9047\u5230_0

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>com.selenium</groupId>  <artifactId>wushuaiTest</artifactId>  <version>0.0.1-SNAPSHOT</version>  <packaging>jar</packaging>  <name>wushuaiTest</name>  <url>http://maven.apache.org</url>  <properties>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  </properties>  <dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>3.8.1</version>      <scope>test</scope>    </dependency>     <!-- https://mvnrepository.com/artifact/org.testng/testng -->    <dependency>        <groupId>org.testng</groupId>        <artifactId>testng</artifactId>        <version>6.11</version>        <scope>test</scope>    </dependency>     <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->    <dependency>        <groupId>org.seleniumhq.selenium</groupId>        <artifactId>selenium-java</artifactId>        <version>3.4.0</version>    </dependency>    <!-- https://mvnrepository.com/artifact/log4j/log4j -->    <dependency>        <groupId>log4j</groupId>        <artifactId>log4j</artifactId>        <version>1.2.17</version>    </dependency>   </dependencies>   <build>        <plugins>            <plugin>                <groupId>org.apache.maven.plugins</groupId>                    <artifactId>maven-compiler-plugin</artifactId>                    <version>2.3.2</version>                    <configuration>                        <source>1.8.0</source>                        <target>1.8.0</target>                    </configuration>            </plugin>            <plugin>                <groupId>org.apache.maven.plugins</groupId>                <artifactId>maven-surefire-plugin</artifactId>                <version>2.12</version>                <inherited>true</inherited>                <configuration>                <suiteXmlFiles>                    <suiteXMLfile>testNG.xml</suiteXMLfile>                </suiteXmlFiles>                </configuration>            </plugin>        </plugins>    </build></project>

testNG.xml

非多线程:

<?xml version="1.0" encoding="UTF-8"?><suite name="Suite" parallel="false">    <parameter name ="username" value="m13031155057@163.com"/>    <parameter name ="password" value="qw150831"/>  <test name="Test1">    <classes>      <class name="com.selenium.wushuaiTest.AppTest"/>      <class name="com.selenium.wushuaiTest.testCase.SuiteTestLogin"/>      <class name="com.selenium.wushuaiTest.testCase.SuiteTestBuy"/>    </classes>  </test></suite>

多线程:

<?xml version="1.0" encoding="UTF-8"?><suite name="Suite" parallel="true" thread-count="2">    <parameter name ="username" value="m13031155057@163.com"/>    <parameter name ="password" value="qw150831"/>  <test name="Test1">    <classes>      <class name="com.selenium.wushuaiTest.AppTest"/>      <class name="com.selenium.wushuaiTest.testCase.SuiteTestLogin"/>      <class name="com.selenium.wushuaiTest.testCase.SuiteTestBuy"/>    </classes>  </test>  <test name="Test2">    <classes>      <class name="com.selenium.wushuaiTest.AppTest"/>      <class name="com.selenium.wushuaiTest.testCase.SuiteTestLogin"/>    </classes>  </test></suite>
原创粉丝点击