selenium 数据驱动测试

本文档展示了如何使用TestNG进行数据驱动测试,详细解释了两种方法:一是直接在测试类中定义数据提供者,二是结合CSV文件进行数据驱动。通过这两个方法,可以有效地导入和删除卡片类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:使用TestNG进行数据驱动

package xxx

import java.util.List;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import util.AdminUtil;
import util.ElementInspector;
import util.Log;
/**
 * 
 * @author xxx 
 * Objective: Import all card types which are need on client test.
 */
public class importCardTypeOnCF {
    private WebDriver driver;
    private StringBuffer verificationErrors = new StringBuffer();

    @DataProvider(name = "data1")
    public Object[][] createdata() {
        return new Object[][] {
                { "Auto.piat.aic.sampleodata.action", "\"C:/automation/script/CF/upfileActionCF.exe\"" },
                { "Auto.piat.aic.sampleodata.createItem", "\"C:/automation/script/CF/upfileCreateItemCF.exe\"" },
                };
    }

    @BeforeClass(alwaysRun = true)
    @Parameters({"landscape","userName","passWord"})
    public void setUp(String landscape, String userName, String passWord) throws Exception {
        AdminUtil adminutil = new AdminUtil();
        adminutil.loginOnCF(landscape, userName, passWord);
        driver = adminutil.getDriver();
    }

    @Test(dataProvider = "data1")
    public void importCardTypes(String CardTypeName, String uploadPath) throws Exception {

        Thread.sleep(3000);
        System.out.println("Start to import " + CardTypeName);
        Log.getLogger().info("Start to import " + CardTypeName);
        // Search by card type name, if exist, do nothing, else create the
        // cardtype
        WebElement searchInputbox = driver.findElement(By.xpath(ElementInspector.Search_Inputbox));
        searchInputbox.clear();
        Thread.sleep(3000);
        searchInputbox.sendKeys(CardTypeName);
        Thread.sleep(3000);
        WebElement tbody = driver
                .findElement(By.xpath(ElementInspector.Table_CardType));
        List<WebElement> tr = tbody.findElements(By.tagName("tr"));
        WebElement tr1 = tr.get(0);
        if (tr1.findElement(By.className("xxxMListTblCell")).getText().equalsIgnoreCase(CardTypeName)) {
            System.out.println(CardTypeName + " is already exist on the landscape.");
            Log.getLogger().info(CardTypeName + " is already exist on the landscape.");
            return;
        } else {
            // create new card type button
            WebElement createCardType = driver
                    .findElement(By.xpath(ElementInspector.BUTTON_Create_CardType));
            createCardType.click();
            Thread.sleep(4000);
            // input card type name
            WebElement cardTypeName = driver
                    .findElement(By.xpath(ElementInspector.Name_CardType));
            cardTypeName.sendKeys(CardTypeName);
            Thread.sleep(4000);
            WebElement fileUploadPath = driver.findElement(By.xpath(ElementInspector.CF_Button_Upload));
            fileUploadPath.sendKeys(Keys.ENTER);
            Thread.sleep(3000);
            openExe(uploadPath);
            Thread.sleep(3000);
            //if waring dialog pops up, click OK to confirm
            if (CardTypeName.equalsIgnoreCase("Auto.piat.aic.sampleodata"))
            {
                driver.findElements(By.tagName("button")).get(0).sendKeys(Keys.ENTER);
            Thread.sleep(3000);
            }
            
            WebElement SaveBtn = driver.findElement(By.xpath(ElementInspector.Button_Save_CardType));
            SaveBtn.click();
            Thread.sleep(5000);
            List<WebElement> btnList = driver.findElements(By.tagName("button"));
            btnList.get(1).sendKeys(Keys.ENTER);
            new WebDriverWait(driver, 300).until(ExpectedConditions.presenceOfElementLocated(By.xpath(ElementInspector.BUTTON_Create_CardType)));
            System.out.println(CardTypeName + " is created successfully.");
            Log.getLogger().info(CardTypeName + " is already exist on the landscape.");
        }
    }

    @Test(dataProvider = "data1")
    public void deleteCardTypes(String CardTypeName,String uploadPath) throws Exception {
        Thread.sleep(3000);
        System.out.println("Starting to delete " + CardTypeName);
        // Search by card type name, if exist, delete it
        WebElement searchInputbox = driver.findElement(By.xpath(ElementInspector.Search_Inputbox));
        searchInputbox.clear();
        Thread.sleep(3000);
        searchInputbox.sendKeys(CardTypeName);
        Thread.sleep(3000);
        WebElement tbody = driver
                .findElement(By.xpath(ElementInspector.Table_CardType));
        List<WebElement> tr = tbody.findElements(By.tagName("tr"));
        WebElement tr1 = tr.get(0);
        if (tr1.findElement(By.className("xxxMListTblCell")).getText().equalsIgnoreCase(CardTypeName)) {
            // delete it
            WebElement dltBtn = driver.findElement(By.cssSelector("button[title='Delete an xxx Custom Card']"));
            dltBtn.click();
            Thread.sleep(3000);
            List<WebElement> dltBtnList2 = driver.findElements(By.tagName("button"));
            dltBtnList2.get(0).click();
            Thread.sleep(8000);
            System.out.println(CardTypeName + " is deleted.");
            return;
        } else {
            System.out.println(CardTypeName + " is not exist.");
        }
    }
    

    public static void openExe(String s) {
        Runtime rn = Runtime.getRuntime();
        Process p = null;
        try {
            p = rn.exec(s);
            Thread.sleep(3000);
        } catch (Exception e) {
            System.out.println("Error exec!");
        }
    }

    @AfterClass(alwaysRun = true)
    public void tearDown() throws Exception {
        driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }
}
方法二:使用TestNG+CSV文件进行数据驱动

package xxx;

import org.testng.annotations.*;
import static org.testng.Assert.*;

import java.util.List;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.openqa.selenium.*;
import util.AdminUtil;

/**
 * 
 * @author xxx
 * Objective: Import all card types which are need on client test.
 */
public class importCardType {
    private WebDriver driver;
    private StringBuffer verificationErrors = new StringBuffer();
    AdminUtil adminutil = new AdminUtil();
    String landscapeURL;

    @DataProvider(name = "testData")
    public Object[][] cardTypeCrt() throws IOException {
        return getTestData("C:\\automation\\testdata\\testData.csv");
    }
    @DataProvider(name = "testDataJS")
    public Object[][] cardTypeCrtJS() throws IOException {
        return getTestData("C:\\automation\\testdata\\testDataJS.csv");
    }
    
    @Parameters({"landscape","userName","passWord"})
    @BeforeClass(alwaysRun = true)
    public void setUp(String landscape, String userName, String passWord) throws Exception {
        adminutil.loginOnNEO(landscape, userName, passWord);
        driver = adminutil.getDriver();
        landscapeURL = landscape;
    }
    
    @Test(dataProvider = "testData")
    public void importCardTypesByCSV(String CardTypeName, String uploadPath) throws Exception {
        adminutil.importCardTypes(CardTypeName, uploadPath);
    }
    
    @Test(dataProvider = "testDataJS")
    public void importCardTypesJSByCSV(String CardTypeName, String uploadPath) throws Exception {
        adminutil.importJScardTypes(CardTypeName, uploadPath);
    }
    public static Object[][] getTestData(String fileName) throws IOException{
        List<Object[]> records = new ArrayList<Object[]>();
        String record;
        BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
        file.readLine();
        while((record=file.readLine())!=null){
            String fields[] = record.split(",");
            records.add(fields);
        }
        file.close();
        Object[][] results = new Object[records.size()][];
        for(int i=0; i<records.size();i++)
        {
            results[i] =records.get(i);
        }
        return results;
    }
    
    
    @Test(dataProvider = "testData")
    public void deleteCardTypesByCSV(String CardTypeName, String uploadPath) throws Exception{
        adminutil.deleteCardTypes(CardTypeName, uploadPath);
    }
    @Test(dataProvider = "testDataJS")
    public void deleteCardTypesJSByCSV(String CardTypeName, String uploadPath) throws Exception{
        adminutil.deleteCardTypes(CardTypeName, uploadPath);
    }
    public static void openExe(String s) {
        Runtime rn = Runtime.getRuntime();
        Process p = null;
        try {
            p = rn.exec(s);
            Thread.sleep(3000);
        } catch (Exception e) {
            System.out.println("Error exec!");
        }
    }

    @AfterClass(alwaysRun = true)
    public void tearDown() throws Exception {
        driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }
}
===================below is adminuitl class for importCardTypes method===================

public void importCardTypes(String CardTypeName, String uploadPath) throws Exception {
        Thread.sleep(3000);
        System.out.println("Start to import " + CardTypeName);
        Log.getLogger().info("Start to import " + CardTypeName);
        // Search by card type name, if exist, do nothing, else create the
        // cardtype
        WebElement searchInputbox = driver.findElement(By.xpath(ElementInspector.Search_Inputbox));
        searchInputbox.clear();
        Thread.sleep(3000);
        searchInputbox.sendKeys(CardTypeName);
        Thread.sleep(3000);
        WebElement tbody = driver.findElement(By.xpath(ElementInspector.Table_CardType));
        List<WebElement> tr = tbody.findElements(By.tagName("tr"));
        WebElement tr1 = tr.get(0);
        if (tr1.findElement(By.className("xxxMListTblCell")).getText().equalsIgnoreCase(CardTypeName)) {
            System.out.println(CardTypeName + " is already exist on the landscape.");
            Log.getLogger().info(CardTypeName + " is already exist on the landscape.");
            return;
        } else {
            try {
                WebElement createCardType = driver.findElement(By.xpath(ElementInspector.BUTTON_Create_CardType));
                createCardType.click();
                Thread.sleep(8000);
                WebElement cardTypeName = driver.findElement(By.xpath(ElementInspector.Name_CardType));
                cardTypeName.click();
                cardTypeName.sendKeys(CardTypeName);
                Thread.sleep(3000);
                driver.findElement(By.id(ElementInspector.Button_Upload)).click();
                Thread.sleep(3000);
                openExe(uploadPath);
                Thread.sleep(3000);
                WebElement SaveBtn = driver.findElement(By.xpath(ElementInspector.Button_Save_CardType));
                SaveBtn.click();
                Thread.sleep(3000);
//                List<WebElement> btnList = driver.findElements(By.tagName("button"));
//                btnList.get(0).sendKeys(Keys.ENTER);
                new WebDriverWait(driver, 120).until(
                        ExpectedConditions.presenceOfElementLocated(By.xpath(ElementInspector.BUTTON_Create_CardType)));
                System.out.println(CardTypeName + " is created successfully.");
                Log.getLogger().info(CardTypeName + " is created successfully.");
                
            } catch (Exception ex) {
                System.out.println(CardTypeName + " is failed to be imported.");
                ex.printStackTrace();
                // reset
                driver.navigate().to(landscape + C2GPageURLAppending);
                Thread.sleep(2000);
                WebElement resetBtn = driver.findElement(By.xpath("/html/body/div[1]/div[2]/footer/div/button[3]"));
                new Actions(driver).moveToElement(resetBtn).click();
                resetBtn.sendKeys(Keys.ENTER);
                Thread.sleep(6000);
                driver.navigate().to(landscape + C2GPageURLAppending);
                new WebDriverWait(driver, 60).until(
                        ExpectedConditions.presenceOfElementLocated(By.xpath(ElementInspector.BUTTON_Create_CardType)));
                return;
            }
        }
    }

    public void deleteCardTypes(String CardTypeName, String uploadPath) throws Exception {
        Thread.sleep(3000);
        System.out.println("Starting to delete " + CardTypeName);
        // Search by card type name, if exist, delete it
        WebElement searchInputbox = driver.findElement(By.xpath(ElementInspector.Search_Inputbox));
        searchInputbox.clear();
        Thread.sleep(3000);
        searchInputbox.sendKeys(CardTypeName);
        Thread.sleep(3000);
        try {
            WebElement tbody = driver.findElement(By.xpath(ElementInspector.Table_CardType));
            List<WebElement> tr = tbody.findElements(By.tagName("tr"));
            WebElement tr1 = tr.get(0);
            if (tr1.findElement(By.className("xxxMListTblCell")).getText().equalsIgnoreCase(CardTypeName)) {
                // delete it
                WebElement dltBtn = driver.findElement(By.cssSelector("button[title='Delete an xxx Custom Card']"));
                dltBtn.click();
                Thread.sleep(3000);
                List<WebElement> dltBtnList2 = driver.findElements(By.tagName("button"));
                dltBtnList2.get(0).click();
                new WebDriverWait(driver, 300).until(
                        ExpectedConditions.presenceOfElementLocated(By.xpath(ElementInspector.BUTTON_Create_CardType)));
                System.out.println(CardTypeName + " is deleted.");
                return;
            } else {
                System.out.println(CardTypeName + " is not exist.");
            }
        } catch (Exception ex) {
            System.out.println(CardTypeName + " is failed to be deleted.");
            ex.printStackTrace();
            // reset
            driver.navigate().to(landscape + C2GPageURLAppending);
            new WebDriverWait(driver, 60).until(
                    ExpectedConditions.presenceOfElementLocated(By.xpath(ElementInspector.BUTTON_Create_CardType)));
            return;
        }
    }
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值