更优秀的 Fluent Selenium + Extent Reports 打造Web自动化测试-错误自动截图

Fluent Selenium介绍

Fluent Selenium是 selenium 官方封装的另一个库, 由于它更加方便的 API, 运用起来非常方便, 写出来的代码也非常易读. 如果不想弄懂负载的 selenium 是如何工作或者如何去实现一个网页的自动化测试的, 用 Fluent Selenium 则是非常不错的一个选择. 配合后面的测试结果报告框架, 使得整个测试强大又高大上!

Fluent Selenium在 GitHub 上有一些基本的用法, 它的 Read me 写的还是非常有用的. 点击这里可以快速去到 GithHub翻看介绍和源码.

Extent Reports

通常我们需要收集一个自动化程序跑完后的结果, 包括测试覆盖率, 通过率, 错误日志, 错误屏幕截图等等. Extent Reports 就很好的为我们做到了这一点. 它不仅可以帮我们自动地收集各种测试结果数据, 还能只能地生成 html 结果文档, PDF 结果文档更或者是邮件和其他形式都可以, 只需要简单的配置.

而且Extent Reports生成出来的测试报告也是相当的专业, 自带各种结果搜索, 报表, 图形化的数据表格等等. 大家可以去它的官方网站查看一些 demo 或者文档.

使用Fluent Selenium + Extent Reports实现一个自动化网页测试

这里我们选用 Maven 来构建项目, 添加相关的依赖包即可(版本大家可以自行去搜索最新的):

<dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.relevantcodes</groupId>
            <artifactId>extentreports</artifactId>
            <version>2.41.2</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium.fluent</groupId>
            <artifactId>fluent-selenium</artifactId>
            <version>1.16.1</version>
            <!-- 自带的版本比较低, 我们可以自己配置高版本 -->
            <exclusions>
                <exclusion>
                    <groupId>org.seleniumhq.selenium</groupId>
                    <artifactId>selenium-java</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

然后我们开始进入正题:

假设我们打开 http://www.jd.com/ 然后搜索 “自动化测试” 的关键字, 查看第一个结果是不是我们想要的书( 假定期待的结果是, 第一个为 “Java” 的书).

首先下载一个 WebDriver可以去网上搜索, 建议下载一个 chrome web driver.

上代码:

System.setProperty("webdriver.chrome.driver", "/path/to/your/webDriver");

这段代码必须先执行, 让系统知道你的 webDriver 在哪里, 程序才知道启动浏览器进行操作.当然你可以选择 FireFox 或者其他浏览器的 Driver , 我这里以 Chrome 为例.

//先声明一个测试开始, 记录日志 true 代表是否在已有日志文件上继续记录
ExtentReports report = new ExtentReports("/make/a/path/reports.html", true);
ExtentTest extentTest = report.startTest("title", "description");

//创建 webDriver 实例, 并最大化网页
WebDriver webDriver = new ChromeDriver();
webDriver.manage().window().maximize();
//打开目标网页 记录步奏日志
webDriver.get("http://www.jd.com/");
extentTest.log(LogStatus.INFO, "打开 http://www.jd.com/");

FluentWebElement resultElement = HomeValidator.searchAndGetResult(extentTest, "自动化测试", "Java");

其中 HomeValidator 做了搜索和获得结果的验证

public FluentWebElement searchAndGetResult(ExtentTest extentTest, String keyWord, String itemName) {
        //代码不全, webDriver 请自行传入
        FluentWebDriver fluentWebDriver = new FluentWebDriver(webDriver);
       
        fluentWebDriver
                .input(id("search box DOM id"))//找到搜索框 id
                .sendKeys(keyWord);//输入想要搜索的关键词
        //继续记录日志
        extentTest.log(LogStatus.INFO, "input search key word '" + keyWord + "'");

        fluentWebDriver
                .div(className("input box div class name"))
                .input(className("search button class name"))
                .click();//定位到搜索按钮并且点击
        extentTest.log(LogStatus.INFO, "click search button");

        FluentWebElements resultList = fluentWebDriver
                .within(secs(30))//等待30秒响应时间
                .ul(id("result ul id"))
                .lis();//返回所有的搜索结果 DOM li

       //返回满足条件的第一个 
       return resultList.first((webElement, ix) -> webElement.has().link(linkText(itemName)));
    }

这样我们就得到了满足条件的第一个, 如果不是 null, 那么就找到了, 相反就没找到, 报错截图, 我们可以定义所有失败后的一个 handle 类, 错误都在那里处理, 进行记录和切图:

切图方法, 返回图片地址:

public String takeScreenShot(WebDriver webDriver) {
        File screenCapture = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
        String filePath = REPORT_FOLDER + createRandomErrorPicName();
        File saveFile = new File(filePath);
        try {
            FileUtils.copyFile(screenCapture, saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return saveFile.getAbsolutePath();
    }

假如 extent report中, 并记录日志, 完成这一个单个测试:

public void takeErrorReport(ExtentTest extentTest, String screenPic, Exception e) {
        extentTest.log(LogStatus.ERROR, e.getMessage());
        extentTest.log(LogStatus.ERROR, "Error Snapshot : " + extentTest.addScreenCapture(screenPic));
        report.endTest(extentTest);
    }

最后不要忘记输入测试结果:

webDriver.quit();
report.flush();

其他问题- selenium新开窗口

很多初学者在写自动化测试程序的时候, 都会遇到新开窗口的问题. 新开窗口会导致上下文发生变化, 当前的网页环境变化了, 很多变量将发生改变, 不再指向当前窗口. 我们需要手动告诉 selenium, 窗口发生了变化:

public void switchToNewWindow(String windowTitle) {
        Set<String> windowHandles = webDriver.getWindowHandles();
        String currentWindowHandle = webDriver.getWindowHandle();

        boolean switchSuccess = false;
        for (String windowHandle : windowHandles) {
            if (!windowHandle.equals(currentWindowHandle)) {
                webDriver.switchTo().window(windowHandle);
                if (webDriver.getTitle().equals(windowTitle)) {
                    switchSuccess = true;
                    break;
                }
            }
        }

        if (!switchSuccess) {
            throw new InvalidArgumentException("window title not exist!");
        }
    }

其中我们必须要知道新窗口的 window title, 然后每次跳转新窗口是, 都必须执行一次切换方法, 告诉 selenium 我们更换了窗口, 请它更新上下文变量.

最后告诉日志, 我们的测试完成啦!并且通过啦!

extentTest.log(LogStatus.PASS, "test successfully!");

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Scroll to Top