慕课网web自动化测试实战之账号登录(四)

慕课网web自动化测试实战

账号登录

需求:

1、项目实战中使用PO模型的设计与封装,详情见PO模型介绍
2、基类的封装,包括:BaseDriver、ByLocation、SelectDriver
3、使用testng测试框架
4、使用log4j打印日志,配置见博文
5、使用testng-xslt生成测试报告,配置见博文

PO模型的基本思路:

LoginPage(查找页面元素类) —>LoginPageHandle(操作层,将查找到的元素位置上传递数据) —> LoginPageBusiness(业务层:调用操作层,根据操作层的传递的结果进行判断场景,如邮箱错误场景等) —> LoginCase(封装调用业务层,进行测试用例的场景组装)

Page层

1、page基类BasePage

package page;

import base.BaseDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

/**
 * page层:页面元素的基类,对元素的定位、点击、输入、是否显示的功能进行封装
 */
public class BasePage {
    public BaseDriver baseDriver;
    public BasePage(BaseDriver driver){
        this.baseDriver=driver;
    }

    /**
     * 定位Element
     */
    public WebElement element(By by){
        WebElement element=baseDriver.findElement(by);
        return element;
    }

    /**
     * 元素的点击事件
     */
    public void click(WebElement element){
        if (element!=null){
            element.click();
        }else {
            System.out.println("元素不能点击!");
        }
    }
    /**
     * 封装输入sendkeys
     */
    public void sendKeys(WebElement element,String value){
        if (element!=null){
            element.sendKeys(value);
        }else {
            System.out.println("输入失败");
        }
    }

    /**
     * 判断元素是否显示
     */
    public boolean assertElement(WebElement element){
        return element.isDisplayed();
    }
}

2、登录页面LoginPage

package page;

import base.BaseDriver;
import base.ByLocation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import java.io.IOException;

/**
 * 功能:登录的界面类,用于获取元素element
 */
public class LoginPage extends BasePage{

    public LoginPage(BaseDriver driver) {
        super(driver);
    }
    //获取用户名输入框element
    public WebElement getUserElement() throws IOException {
        return element(ByLocation.getLocator("userString"));
    }
    //获取密码输入框element
    public WebElement getPasswordElement() throws IOException {
        return element(ByLocation.getLocator("passwordString"));
    }
    //获取登录按钮element
    public WebElement getLoginButtonElement() throws IOException {
        return element(ByLocation.getLocator("loginButtonString"));
    }
    //获取自动登录element
    public WebElement getAutoSigninElement() throws IOException {
        return element(ByLocation.getLocator("autoSignin"));
    }
}

handle操作层
package handle;

import base.BaseDriver;
import page.LoginPage;

import java.io.IOException;

/**
 * 登录页面的操作类,用于输入内容、点击事件等
 */
public class LoginPageHandle {
    public BaseDriver driver;
    public LoginPage loginPage;
    public LoginPageHandle(BaseDriver driver){
        this.driver=driver;
        loginPage=new LoginPage(driver);
    }
    //输入用户名
    public void sendKeyUser(String username) throws IOException {
        loginPage.sendKeys(loginPage.getUserElement(),username);
    }
    //输入密码
    public void sendKeyPassword(String password) throws IOException {
        loginPage.sendKeys(loginPage.getPasswordElement(),password);
    }
    //登录的点击事件
    public void clickLoginButton() throws IOException {
        loginPage.click(loginPage.getLoginButtonElement());
    }
    //选中自动登录
    public void clickAutoSignin() throws IOException {
        loginPage.click(loginPage.getAutoSigninElement());
    }
    //判断是否是登录界面
    public boolean assertLoginPage() throws IOException {
        return loginPage.assertElement(loginPage.getUserElement());
    }
}

business业务层
package business;

import base.BaseDriver;
import handle.LoginPageHandle;

import java.io.IOException;

/**
 * 功能:登录的业务层,将多个元素操作组合起来,实现一个业务功能
 */
public class LoginPageBusiness {
    public LoginPageHandle handle;
    public LoginPageBusiness(BaseDriver driver){
        handle=new LoginPageHandle(driver);
    }
    public void login(String username,String password) throws IOException {
        //判断是否是登录界面
        if (handle.assertLoginPage()){
            //实现业务
            handle.sendKeyUser(username);
            handle.sendKeyPassword(password);
            handle.clickAutoSignin();
            handle.clickLoginButton();
        }else {
            System.out.println("页面不存在,请检查网络!");
        }
    }
}

设置基类,方便模块调用

1、BaseDriver

package base;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;

import java.io.File;
import java.io.IOException;

/**
 * Driver的基类
 */
public class BaseDriver {
    WebDriver driver;
    public BaseDriver(String browser){
        SelectDriver selectDriver=new SelectDriver();
        this.driver = selectDriver.driverName(browser);
    }
    /**
     * 截图功能
     */
    public void takeScreenShot() throws IOException {
        //获取的是当前的系统时间(以时间作为截图的文件名)
        long time=System.currentTimeMillis();
        String imageTime=String.valueOf(time);
        imageTime=imageTime+".png";
        //获取当前工程路径
        String currentPath=System.getProperty("user.dir");
        //截图存放路径为=工程路径+文件名
        String screenPath=currentPath+"/"+imageTime;
        //截图函数getScreenshotAs()来截取当前窗口
        File screen=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(screen,new File(screenPath));  //文件名复制到截图
    }
    //关闭driver
    public void stop(){
        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);
    }
}

2、SelectDriver

package 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){
        if (browser.equalsIgnoreCase("firefox")){
            return new FirefoxDriver();
        }else {
            return new ChromeDriver();
        }
    }
}

3、ByLocation

package base;

import org.openqa.selenium.By;
import util.PropertyUtil;
import java.io.IOException;

/**
 * 功能:定位方式的封装,读取配置文件,返回元素的属性值
 */
public class ByLocation {
    public static By getLocator(String key) throws IOException {
        //使用配置文件中的html元素属性数据(key->value)
        PropertyUtil propertyUtil=new PropertyUtil("element.properties");
        String locator=propertyUtil.getProperty(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("partialLinkText")){
            return By.partialLinkText(locatorValue);
        }else if(locatorType.equals("tagName")){
            return By.tagName(locatorValue);
        }else if (locatorType.equals("cssSelector")){
            return By.cssSelector(locatorValue);
        }else{
            return By.xpath(locatorValue);
        }
    }
}

读取配置文件的页面元素属性值

1、配置文件element.properties

#key->value

advert=cssSelector>.redrain-closeBtn
come_login=xpath>.//*[@id='js-signin-btn']
userString=name>email
passwordString=name>password
loginButtonString=cssSelector>.moco-btn.moco-btn-red.moco-btn-lg.btn-full.xa-login
autoSignin=id>auto-signin
headString=xpath>.//*[@id='header-avator']/img
userIDString=xpath>.//*[@id='header-user-card']/div/div/div[1]/div/a/span

2、 读取配置文件工具类

package util;

import java.io.*;
import java.util.Properties;

/**
 * 定位元素数据存入的配置文件的工具类
 */
public class PropertyUtil {
    private Properties properties;
    private String filePath;//配置文件的路径
    public PropertyUtil(String filePath) throws IOException {
        this.filePath=filePath;
        this.properties=readProperties();
    }

    /**
     * 读取配置文件
     */
    private Properties readProperties() throws IOException {
        properties=new Properties();
        InputStream inputStream=new FileInputStream(filePath);
        BufferedInputStream inputStream1=new BufferedInputStream(inputStream);
        //load方法其实就是传进去一个输入流,字节流或者字符流
        properties.load(inputStream);
        return properties;
    }

    /**
     * 获取配置文件中的指定数据
     */
    public String getProperty(String key) throws IOException {
        if (properties.containsKey(key)) {
            String userString=properties.getProperty(key);
            return userString;
        }else {
            System.out.println("你获取的key不存在");
            return "";
        }
    }
}

设计测试用例代码

1、BaseCase

package testCase;

import base.BaseDriver;

/**
 * 功能:用例的基类,初始化Driver
 */
public class CaseBase {
    public BaseDriver InitDriver(String browser){
        return new BaseDriver(browser);
    }

}

2、登录测试用例LoginCase

package testCase;

import base.BaseDriver;
import business.LoginPageBusiness;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import java.io.IOException;


/**
 * 登录慕课网自动化测试用例
 */
public class LoginCase extends CaseBase{
    public BaseDriver driver;
    public LoginPageBusiness loginPageBusiness;
    static Logger logger= Logger.getLogger(LoginCase.class);
    public LoginCase(){
        this.driver=InitDriver("firefox");
        loginPageBusiness=new LoginPageBusiness(driver);
    }
    //慕课网点击登录链接,进入登录界面
    @Test
    public void getLoginHome() throws InterruptedException {
        driver.get("https://www.imooc.com/");
        Thread.sleep(3000);
        driver.findElement(By.cssSelector(".redrain-closeBtn")).click();
        Thread.sleep(2000);
        driver.findElement(By.id("js-signin-btn")).click();
        Thread.sleep(3000);
    }
    //测试登录界面
    @Test(dependsOnMethods = {"getLoginHome"})
    public void testLogin() throws IOException, InterruptedException {
//        logger.debug("这是一条log4j日志");
        logger.info("这是一条log4j日志");
//        logger.error("这是一条log4j error日志");
        loginPageBusiness.login("[email protected]","dpl12345");
        Thread.sleep(2000);
        driver.stop();
    }
}

实现效果:

在这里插入图片描述

生成HTML报告

在这里插入图片描述
代码

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章