首页 > 其他分享 >基于Selenium+webdriver对Web应用系统进行功能测试

基于Selenium+webdriver对Web应用系统进行功能测试

时间:2024-05-27 15:31:51浏览次数:27  
标签:webdriver Web driver WebElement 功能测试 findElement id click wait

以Java格式的脚本,在JUnit框架上执行和调试这些脚本。

项目语言与架构选项为5447406daaa742f4ad256ff6f4f23ae9.png

pom.xml中添加的依赖59d74d8d809c4cc08731f32690edf0f6.png

在kotlin目录中添加Java类,开始编写测试代码:

找到chrome的版本并下载对应版本的chromedriver,在setProperty中将chromedriver.exe的路径完善后就可以开始测试。

chromedriver全版本链接

chromedriver.storage.googleapis.com/index.html

适用于125及之后版本的chromedriver

ChromeDriver Latest Releases Versions Downloads - Chrome for Testing availability (getwebdriver.com)

以下是包括了13个测试类的代码:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class SauceDemoTest {
    private WebDriver driver;

    @Before
    public void setUp() {
        // 设置ChromeDriver路径
        System.setProperty("webdriver.chrome.driver", "//path//chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.saucedemo.com/");
    }

    @After
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
    // 测试用例
    // 登录成功
    @Test
    public void testLoginWithValidCredentials() {
        WebElement usernameField = driver.findElement(By.id("user-name"));
        WebElement passwordField = driver.findElement(By.id("password"));
        WebElement loginButton = driver.findElement(By.id("login-button"));

        usernameField.sendKeys("standard_user");
        passwordField.sendKeys("secret_sauce");
        loginButton.click();

        assertTrue(driver.findElement(By.className("title")).isDisplayed());
    }

        // 登录失败
    @Test
    public void testLoginWithInvalidCredentials() {
        WebElement usernameField = driver.findElement(By.id("user-name"));
        WebElement passwordField = driver.findElement(By.id("password"));
        WebElement loginButton = driver.findElement(By.id("login-button"));

        usernameField.sendKeys("invalid_user");
        passwordField.sendKeys("invalid_password");
        loginButton.click();

        assertTrue(driver.findElement(By.xpath("//h3[contains(text(),'Epic sadface')]")).isDisplayed());
    }
        // 登录失败,输入空用户名和密码
    @Test
    public void testLoginWithEmptyCredentials() {

        WebElement loginButton = driver.findElement(By.id("login-button"));
        loginButton.click();

        assertTrue(driver.findElement(By.xpath("//h3[contains(text(),'Epic sadface')]")).isDisplayed());
    }
    // 添加商品到购物车
    @Test
    public void testAddProductToCart() {
        testLoginWithValidCredentials();
        // 创建一个WebDriverWait对象,设置最长等待时间为10秒
        WebDriverWait wait = new WebDriverWait(driver, 10);
        // 获取商品添加到购物车按钮
        WebElement addToCartButton = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Add to cart')]")));
        addToCartButton.click();
        // 获取购物车数量
        WebElement cartBadge = wait.until(ExpectedConditions.elementToBeClickable(By.className("shopping_cart_badge")));

        assertEquals("1", cartBadge.getText());
    }
     //验证购物车数量更新
    @Test
    public void testRemoveProductFromCart() {
        testAddProductToCart();
        WebDriverWait wait = new WebDriverWait(driver, 10);
        WebElement removeFromCartButton = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Remove')]")));
        removeFromCartButton.click();

        boolean isCartBadgePresent = driver.findElements(By.className("shopping_cart_badge")).size() > 0;
        assertTrue(!isCartBadgePresent);
    }
    //验证购物车数量更新
//    @Test
//    public void testUpdateProductQuantityInCart() {
//        testAddProductToCart();
//        WebElement cartButton = driver.findElement(By.className("shopping_cart_link"));
//        cartButton.click();
//
//        WebElement quantityField = driver.findElement(By.className("cart_quantity"));
//        assertEquals("1", quantityField.getText());
//
//        WebElement continueShoppingButton = driver.findElement(By.id("continue-shopping"));
//        continueShoppingButton.click();
//
//        WebElement addToCartButton = driver.findElement(By.xpath("//button[contains(text(),'Add to cart')]"));
//        addToCartButton.click();
//
//        cartButton.click();
//        quantityField = driver.findElement(By.className("cart_quantity"));
//        assertEquals("2", quantityField.getText());
//    }
       //验证购物车总价计算
    @Test
    public void testCartTotalPriceCalculation() {
        testLoginWithValidCredentials();
        // 创建一个WebDriverWait对象,设置最长等待时间为10秒
        WebDriverWait wait = new WebDriverWait(driver, 10);
        WebElement addToCartButton1 = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Add to cart')]")));
        addToCartButton1.click();
        WebElement addToCartButton2 = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Add to cart')]")));
        addToCartButton2.click();

        WebElement cartButton = wait.until(ExpectedConditions.elementToBeClickable(By.className("shopping_cart_link")));
        cartButton.click();
        // 获取第一个商品价格

        List<WebElement> productPrices = driver.findElements(By.className("inventory_item_price"));

            // 获取第一个商品价格
            WebElement firstItemPrice = productPrices.get(0);

            // 获取第二个商品价格
            WebElement secondItemPrice = productPrices.get(1);

            // 现在你可以对这两个元素进行操作了,例如打印它们的文本内容
            System.out.println("First item price: " + firstItemPrice.getText());
            System.out.println("Second item price: " + secondItemPrice.getText());


        // 计算总价

        double totalPrice = Double.parseDouble(firstItemPrice.getText().substring(1)) +
                Double.parseDouble(secondItemPrice.getText().substring(1));
        //System.out.println("预期结果: "+ "Item total: $" + totalPrice);
        // 验证总价标签内容
        WebElement checkoutButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("checkout")));
        checkoutButton.click();
        WebElement firstNameField = driver.findElement(By.id("first-name"));
        WebElement lastNameField = driver.findElement(By.id("last-name"));
        WebElement postalCodeField = driver.findElement(By.id("postal-code"));
        WebElement continueButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("continue")));


        firstNameField.sendKeys("John");
        lastNameField.sendKeys("Doe");
        postalCodeField.sendKeys("12345");

        continueButton.click();

//        WebElement finishButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("finish")));
//        finishButton.click();
        // 获取总价标签
        WebElement total = wait.until(ExpectedConditions.elementToBeClickable(By.className("summary_subtotal_label")));
        //WebElement total = driver.findElement(By.className("summary_total_label"));

        // 验证总价标签内容
        //System.out.println("实际结果: " + total.getText());

        assertEquals(String.format("Item total: $%.2f",+ totalPrice), total.getText());

    }
    @Test
    public void testCartTotalPriceCalculation1() {
        testLoginWithValidCredentials();
        // 创建一个WebDriverWait对象,设置最长等待时间为10秒
        WebDriverWait wait = new WebDriverWait(driver, 10);
        WebElement addToCartButton1 = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Add to cart')]")));
        addToCartButton1.click();
        WebElement addToCartButton2 = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Add to cart')]")));
        addToCartButton2.click();

        WebElement cartButton = wait.until(ExpectedConditions.elementToBeClickable(By.className("shopping_cart_link")));
        cartButton.click();
        // 获取第一个商品价格


        WebElement firstItemPrice = driver.findElement(By.className("inventory_item_price"));
        WebElement secondItemPrice = driver.findElement(By.className("inventory_item_price"));


        // 计算总价
        double totalPrice = Double.parseDouble(firstItemPrice.getText().substring(1)) +
                Double.parseDouble(secondItemPrice.getText().substring(1));
        // 验证总价标签内容
        WebElement checkoutButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("checkout")));
        checkoutButton.click();
        WebElement firstNameField = driver.findElement(By.id("first-name"));
        WebElement lastNameField = driver.findElement(By.id("last-name"));
        WebElement postalCodeField = driver.findElement(By.id("postal-code"));
        WebElement continueButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("continue")));


        firstNameField.sendKeys("John");
        lastNameField.sendKeys("Doe");
        postalCodeField.sendKeys("12345");

        continueButton.click();

//        WebElement finishButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("finish")));
//        finishButton.click();
        // 获取总价标签
        WebElement total = wait.until(ExpectedConditions.elementToBeClickable(By.className("summary_subtotal_label")));
        //WebElement total = driver.findElement(By.className("summary_total_label"));

        // 验证总价标签内容
        assertEquals(String.format("Item total: $%.2f",+ totalPrice), total.getText());
    }
    //验证结账流程
    @Test
    public void testCheckoutProcess() {
        testAddProductToCart();
        //找到购物车按钮
        WebElement cartButton = driver.findElement(By.className("shopping_cart_link"));
        cartButton.click();
        //找到结账按钮
        WebElement checkoutButton = driver.findElement(By.id("checkout"));
        checkoutButton.click();
        //找名字等输入框
        WebElement firstNameField = driver.findElement(By.id("first-name"));
        WebElement lastNameField = driver.findElement(By.id("last-name"));
        WebElement postalCodeField = driver.findElement(By.id("postal-code"));
        WebElement continueButton = driver.findElement(By.id("continue"));
        //输入名字等信息
        firstNameField.sendKeys("John");
        lastNameField.sendKeys("Doe");
        postalCodeField.sendKeys("12345");
        continueButton.click();
        //找到完成按钮
        WebElement finishButton = driver.findElement(By.id("finish"));
        finishButton.click();
        //找到确认信息
        WebElement confirmationMessage = driver.findElement(By.className("complete-header"));
        assertEquals("Thank you for your order!", confirmationMessage.getText());
    }
    //验证产品列表
    @Test
    public void testViewProductDetails() {
        testLoginWithValidCredentials();
        WebElement productLink = driver.findElement(By.className("inventory_item_name"));
        productLink.click();

        WebElement productTitle = driver.findElement(By.className("inventory_details_name"));
        assertTrue(productTitle.isDisplayed());
    }
    //验证产品排序
    @Test
    public void testProductSorting() {
        testLoginWithValidCredentials();
        // 创建一个WebDriverWait对象,设置最长等待时间为10秒
        WebElement sortDropdown = driver.findElement(By.className("product_sort_container"));
        sortDropdown.click();
        // 找到并点击价格排序按钮
        WebElement sortOption = driver.findElement(By.xpath("//option[contains(text(),'Price (low to high)')]"));
        sortOption.click();
        //找到第一个产品价格
        List<WebElement> productPrices = driver.findElements(By.className("inventory_item_price"));

        // 获取第一个商品价格
        WebElement firstProductPrice = productPrices.get(0);

        // 获取第二个商品价格
        WebElement secondProductPrice = productPrices.get(productPrices.size() - 1);

        double firstPrice = Double.parseDouble(firstProductPrice.getText().substring(1));
        double secondPrice = Double.parseDouble(secondProductPrice.getText().substring(1));

        assertTrue(firstPrice <= secondPrice);
    }
    //验证页面布局
    @Test
    public void testPageLayout() {
        testLoginWithValidCredentials();
        WebElement header = driver.findElement(By.className("header_secondary_container"));
        WebElement footer = driver.findElement(By.className("footer"));
        assertTrue(header.isDisplayed());
        assertTrue(footer.isDisplayed());
    }
    //点击登录按钮,跳转到登录页面
    @Test
    public void testButtonFunctionality() {
        testLoginWithValidCredentials();
        // 创建一个WebDriverWait对象,设置最长等待时间为10秒
        WebDriverWait wait = new WebDriverWait(driver, 10);
        // 等待菜单按钮变得可点击,然后点击它
        WebElement menuButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("react-burger-menu-btn")));
        menuButton.click();
        // 等待登录按钮变得可见并且可点击,然后点击它
        WebElement logoutButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("logout_sidebar_link")));
        logoutButton.click();

        // 找到登录按钮并验证它是否可见
        WebElement loginButton = driver.findElement(By.id("login-button"));
        assertTrue(loginButton.isDisplayed());
    }
    //点击twitter链接,跳转到twitter页面
    @Test
    public void testLinkNavigation() {
        testLoginWithValidCredentials();
        // 创建一个WebDriverWait对象,设置最长等待时间为10秒
        WebDriverWait wait = new WebDriverWait(driver, 10);

        // 等待菜单按钮变得可点击,然后点击它
        WebElement twitterLink = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(@href, 'twitter')]")));
        twitterLink.click();
        // 等待URL包含特定的字符串
        wait.until(ExpectedConditions.urlContains("twitter.com"));
        // 获取当前URL并进行断言
        String currentUrl = driver.getCurrentUrl();
        assertTrue(currentUrl.contains("twitter.com"));//国内禁止访问twitter因此这里用contains判断后会无法访问,属于测试正常失败
    }
    //测试导航到about页面
    @Test
    public void testNavigationToAboutPage() {
        testLoginWithValidCredentials();
        // 创建一个WebDriverWait对象,设置最长等待时间为10秒
        WebDriverWait wait = new WebDriverWait(driver, 10);

        // 等待菜单按钮变得可点击,然后点击它
        WebElement menuButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("react-burger-menu-btn")));
        menuButton.click();

        // 等待关于链接变得可见并且可点击,然后点击它
        WebElement aboutLink = wait.until(ExpectedConditions.elementToBeClickable(By.id("about_sidebar_link")));
        aboutLink.click();

        // 等待URL包含特定的字符串
        wait.until(ExpectedConditions.urlContains("saucelabs.com"));

        // 获取当前URL并进行断言
        String currentUrl = driver.getCurrentUrl();
        assertTrue(currentUrl.contains("saucelabs.com"));
    }
    //测试搜索产品 这网页就没搜索框你搜啥呢?
//    @Test
//    public void testSearchProduct() {
//        testLoginWithValidCredentials();
//
//        WebElement searchBox = driver.findElement(By.id("search-box"));
//        searchBox.sendKeys("Backpack");
//
//        WebElement searchButton = driver.findElement(By.id("search-button"));
//        searchButton.click();
//
//        WebElement product = driver.findElement(By.xpath("//div[contains(text(),'Backpack')]"));
//        assertTrue(product.isDisplayed());
//    }

}

 

 

 

标签:webdriver,Web,driver,WebElement,功能测试,findElement,id,click,wait
From: https://blog.csdn.net/weixin_69904753/article/details/139232446

相关文章

  • 【CTF Web】CTFShow web9 Writeup(RCE+PHP+代码审计)
    web91阿呆在埃塞俄比亚终于找了一个网管的工作,闲暇时还能种点菜。解法可知flag在config.php。<?php#flaginconfig.phpinclude("config.php");if(isset($_GET['c'])){$c=$_GET['c'];if(preg_match("/system|exec|highlight/i",$c......
  • 【CTF Web】CTFShow web10 Writeup(RCE+PHP+代码审计)
    web101阿呆看见对面二黑急冲冲的跑过来,告诉阿呆出大事了,阿呆问什么事,二黑说:这几天天旱,你菜死了!解法可知flag在config.php。<?php#flaginconfig.phpinclude("config.php");if(isset($_GET['c'])){$c=$_GET['c'];if(!preg_match("/system|......
  • Web Service和Web API理解和使用场景
    WebService理解:WebService是一种基于网络的服务,它使用标准化的消息传递协议,最典型的是基于SOAP(SimpleObjectAccessProtocol)协议。SOAP使用XML格式封装数据,定义了消息的结构和传输方式,因此它是一个重量级的解决方案。WebService支持跨平台、跨语言的通信,常用于企业内......
  • android studio 实现web网站变成app小程序
    MainActivity.javapackagecom.example.myapplication;importandroid.os.Bundle;importandroid.webkit.WebView;importandroid.webkit.WebViewClient;importandroidx.appcompat.app.AppCompatActivity;publicclassMainActivityextendsAppCompatActivity{......
  • Web-请求数据+号丢失问题
    1.背景先来复习下URL请求的基本知识HTTP的早期设计主要考虑了基本的文档检索需求以及表单提交功能,这直接影响了后来对POST请求和内容类型的发展。1.1请求方法HTTP(超文本传输协议)最初设计的目的是为了支持万维网上的文档检索,这涉及到请求HTML页面、图像、视频等静态资源。......
  • 1915springboot VUE 宠物寄养平台系统开发mysql数据库web结构java编程计算机网页源码m
    一、源码特点 springbootVUE宠物寄养平台系统是一套完善的完整信息管理类型系统,结合springboot框架和VUE完成本系统,对理解JSPjava编程开发语言有帮助系统采用springboot框架(MVC模式开发),系统具有完整的源代码和数据库,系统主要采用B/S模式开发。springbootVUE宠物寄养......
  • 【JAVA】Java如何使用Spring Boot进行Web服务开发
    文章目录前言一、函数解释二、代码实现三、总结前言在现代的微服务架构中,创建快速、可靠的Web服务已经成为一项基本技能。SpringBoot是一个出色的框架,它简化了Spring应用开发,使我们能够更快速地创建和部署Web服务。在这篇博客中,我们将探讨如何使用Java和SpringBoo......
  • EAS_WEB获取传参,获取上下文,获取控制单元
    varimp=JavaImporter();imp.importPackage(Packages.java.lang);imp.importPackage(Packages.org.apache.commons.lang3);imp.importPackage(Packages.com.kingdee.bos.webframework.context);imp.importPackage(Packages.com.kingdee.eas.util.app);imp.importPackage(......
  • 在Linux中,如何配置Web服务器(如Apache或Nginx)?
    在Linux系统中配置Web服务器是建立网站托管环境的关键步骤之一。下面将详细介绍如何在Linux中配置两种流行的Web服务器:Apache和Nginx:一、ApacheWeb服务器的配置:安装Apache服务器:首先确认Apache是否已安装在系统上。这可以通过运行rpm-qa|grep-ihttpd(针对RedHat系列)或......
  • Web系列-前端游戏
    Web系列-前端游戏在CTF比赛web题目中,出题人为了添加趣味性,常有将web小游戏作为题目的,本篇博客会将自己遇到的web前端游戏题目记录在这里。[NewStarCTF2023公开赛道]游戏高手是一个飞机大战的游戏题目说100000分就给flag,F12看看游戏游戏代码在app_v2.js中找到关键代码//......