Skip to content

【线上】web自动化测试

Web 自动化测试

直播前准备

  • 注册自己的企业微信:https://work.weixin.qq.com/wework_admin/register_wx

注意: Java技术栈的同学选择Java班级,Python技术栈的同学选择Python班级。

专题课 阶段 章节 Python 班级 Java 班级
用户端 Web 自动化测试 L1 环境安装与使用 Python版录播 Java版录播
用户端 Web 自动化测试 L1 Web自动化测试价值与体系
用户端 Web 自动化测试 L1 常见控件定位方法
用户端 Web 自动化测试 L1 强制等待与隐式等待
用户端 Web 自动化测试 L1 常见控件交互方法
用户端 Web 自动化测试 L2 高级定位-css
用户端 Web 自动化测试 L2 高级定位-xpath
用户端 Web 自动化测试 L3 Cookie 复用
测试框架与Allure 测试报告 Allure2 测试报告-L1 全部知识点 Python版录播 Java版录播
测试框架与Allure 测试报告 Allure2 测试报告-L1 allure2报告生成

课程目标

  • 熟悉 Selenium 框架与常用操作
  • 掌握 Web 自动化测试用例编写能力
  • 掌握 Web 自动测试实战能力

手工测试与自动化测试对比

uml diagram

uml diagram

Web 自动化测试合适场景

  • 业务流程不频繁改动
  • UI 元素不频繁改动
  • 需要频繁回归的场景
  • 核心场景等

知识点总览

点击查看:web知识点梳理.xmind

需求说明

  • 企业微信是腾讯微信团队打造的企业通讯与办公工具,具有与微信一致的沟通体验,丰富的 OA 应用,和连接微信生态的能力,可帮助企业连接内部、连接生态伙伴、连接消费者。专业协作、安全管理、人即服务。其功能主要包含:企业通讯,文档模块,会议模块,邮件模块,日程模块,微信模块。
  • 完成企业微信的 Web 自动化测试 - 完成企业微信 Web 端自动化用例 - 输出测试报告

实战思路

uml diagram

搭建 Web 自动化测试环境

Selenium 工作原理

  • Selenium WebDriver
  • Selenium IDE
  • Selenium Grid
  • 面试题参考贴:https://ceshiren.com/t/topic/22890

uml diagram

配置 Driver

Python 实现
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

service = Service(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
Java 实现

pom.xml

//判断浏览器是否存在
Optional<Path> browserPath = WebDriverManager.chromedriver().getBrowserPath();
assumeTrue(browserPath.isPresent());

ChromeOptions options = new ChromeOptions();
//防止连接报错
options.addArguments("--remote-allow-origins=*");
//打开浏览器
WebDriver driver = WebDriverManager.chromedriver().capabilities(options).create();

实战:企业微信 Web 端成员添加功能

测试用例

测试模块 用例标题 前置条件 用例步骤 预期结果 实际结果
成员模块 添加成员 登录成功 1. 成功进入添加成员页面
2.输入成员信息点击保存
3.检查成员列表页面
1. 成功添加学员
2. 添加成功的成员展示在成员列表里面
成员模块 添加成员,输入重复账号 登录成功 1. 成功进入添加成员页面
2.输入重复标识的成员信息点击保存
3.检查成员列表页面
1. 添加学员失败提示账号已被占用

测试用例转换为自动化测试脚本

python实现
class TestWeWork:
    def setup_class(self):
        # 初始化 driver
        ...

    def teardown_class(self):
        # 退出浏览器

    def test_add_member(self):
        '''
        测试步骤
        1. 成功进入添加成员页面
        2. 输入成员信息点击保存
        3. 检查成员列表页面
        :return:
        '''
        # 断言 成员 是否在列表里
        ...
java实现
public class AddMemberTest {
    @BeforeAll
    public void login(){
        //进行登录
    }

    @AfterAll
    public void quit(){
        //退出浏览器
    }

    @Test
    public void addMemberTest(){
        /** 测试步骤
         * 1. 成功进入添加成员页面
         * 2.输入成员信息点击保存
         * 3.检查成员列表页面
         */

        //断言成员数据是否在成员列表里面
    }
}

点击查看 Cookie 详解

实战:生成测试报告

Allure 环境搭建

  1. 安装 Java,需要配置环境变量。
  2. 安装 Allure ,需要配置环境变量。

    - 下载地址

      - mac/linux: 下载 tar
    
      - windows: 下载 zip
    

    - 配置环境变量:解压后将 bin 目录加入 PATH 环境变量。

    - 执行命令验证环境:allure --version

    - 详细安装步骤参考:https://ceshiren.com/t/topic/3386

  3. 安装插件:

    - Python:pip install allure-pytest

添加报告描述信息

  • 添加业务描述
  • 添加功能描述
  • 添加测试标题
  • 添加步骤描述
python 实现
@allure.feature("企业微信 web 端")
class TestWeWork:
    def setup_class(self):
        # 初始化 driver
        service = Service(executable_path=ChromeDriverManager().install())
        self.driver = webdriver.Chrome(service=service)
        # 隐式等待
        self.driver.implicitly_wait(10)
        # 最大化窗口
        self.driver.maximize_window()
        self.driver.get('https://work.weixin.qq.com/wework_admin/frame')
        # # 方法一:增加强制等待时间,手动扫码
        # sleep(20)
        # 方法二:
        with open('./cookie.yml', 'r', encoding='utf-8') as f:
            cookies = yaml.safe_load(f)
            for cookie in cookies:
                self.driver.add_cookie(cookie)
        self.driver.get('https://work.weixin.qq.com/wework_admin/frame')

    def teardown_class(self):
        # 退出浏览器
        self.driver.quit()

    @allure.title("企业微信添加成员功能")
    def test_add_member(self):
        '''
        测试步骤
        1. 成功进入添加成员页面
        2. 输入成员信息点击保存
        3. 检查成员列表页面
        :return:
        '''
        with allure.step('点击通讯录按钮'):
            self.driver.find_element(By.ID, 'menu_contacts').click()
        sleep(3)
        with allure.step('点击添加成员按钮'):
            self.driver.find_elements(By.CSS_SELECTOR, ".qui_btn.ww_btn.js_add_member")[1].click()
        sleep(3)
        with allure.step("输入成员信息"):
            self.driver.find_element(By.ID, 'username').send_keys('momo2')
            self.driver.find_element(By.ID, 'memberAdd_acctid').send_keys('momo12345')
            self.driver.find_element(By.ID, 'memberAdd_phone').send_keys('18711111111')
        with allure.step("点击保存按钮"):
            self.driver.find_element(By.CSS_SELECTOR, '.ww_operationBar .js_btn_save').click()
        # 添加断言
        member_list = self.driver.find_elements(By.CSS_SELECTOR, '.member_colRight_memberTable_td:nth-child(2)')
        members = []
        for member in member_list:
            members.append(member.text)
        assert 'momo2' in members
Java 实现
@DisplayName("添加成员测试")
public class AddMemberTest {

    static ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    static WebDriver driver;

    @BeforeAll
    static void login() throws IOException {
        ChromeOptions options = new ChromeOptions();
        //防止连接报错
        options.addArguments("--remote-allow-origins=*");
        driver = new ChromeDriver(options);
        String url = "https://work.weixin.qq.com/wework_admin/frame";
        // 访问企业微信主页
        driver.get(url);
        // 使用 cookie 登录
        // 1.声明一个泛型
        TypeReference<List<HashMap<String, Object>>> typeReference =
                new TypeReference<>() {};
        // 2. 从yaml中获取cookies
        List<HashMap<String, Object>> loadCookies =
                mapper.readValue(new File("cookies.yaml"),
                        typeReference);
        loadCookies.stream()
                // 找到domain包含work.weixin.qq.com
                .filter(cookie -> cookie.get("domain").toString().
                        contains("work.weixin.qq.com"))
                .forEach(cookie -> {
                    driver.manage().addCookie(
                            new Cookie(cookie.get("name").toString(),
                                    cookie.get("value").toString()));
                });
        // 4. 刷新页面,登录成功
        driver.navigate().refresh();
    }

    @AfterAll
    static void close(){
        //等待人工调试时查看结果
        //关闭浏览器
    }

    @Test
    @DisplayName("添加成员冒烟测试")
    void addMember() throws InterruptedException {

        /**
         * 测试步骤
         * 1. 成功进入添加成员页面
         * 2.输入成员信息点击保存
         * 3.检查成员列表页面
         */
        Allure.step("点击通讯录");
        By addressBookBtn = By.linkText("通讯录");
        driver.findElement(addressBookBtn).click();
        sleep(1000);
        Allure.step("点击添加成员");
        By addMemberBtn = By.cssSelector(".ww_operationBar .js_add_member");
        driver.findElement(addMemberBtn).click();
        sleep(1000);
        Allure.step("输入 姓名、账号、手机");
        By usernameInput = By.name("username");
        By accountInput = By.id("memberAdd_acctid");
        By phoneInput = By.xpath("//input[@name=\"mobile\"]");
        String username = "张三";
        String account =  Long.toString(System.currentTimeMillis());
        String phone = account.substring(0,11);
        driver.findElement(usernameInput).sendKeys(username);
        driver.findElement(accountInput).sendKeys(account);
        driver.findElement(phoneInput).sendKeys(phone);
        Allure.step("点击保存");
        By saveBtn = By.xpath("//*[text()=\"保存\"]");
        driver.findElement(saveBtn).click();
        sleep(1000);
        //断言成员数据是否在成员列表里面
        By memberTextItems = By.cssSelector(".member_colRight_memberTable_td");
        List<String> memberTexts = driver.findElements(memberTextItems).stream().map(e -> e.getText()).collect(Collectors.toList());
        assertThat(memberTexts,hasItems(username));
        // 断言预期学员信息是否出现在学员列表中
    }
}

课后练习

  • 要求: 1. 完成成员添加失败自动化测试用例场景 2. 填写相关测试报告、断言 3. 尝试优化强制等待(选做)
  • 实现步骤:参考测试用例

总结

  • Selenium 环境搭建
  • Selenium 自动化脚本编写
  • Cookie 复用登录
  • Allure 报告