数据驱动(1)

什么是数据驱动?

  相同的测试脚本使用不同的测试数据来执行,测试数据和测试行为进行了完全的分离,这样的测试脚本设计模式称为数据驱动。

实施数据驱动测试的步骤如下:

  (1)编写测试脚本,脚本需要支持程序对象、文件或数据库读入测试数据

  (2)将测试脚本使用的测试数据存入程序对象、文件或数据库等外部介质中

  (3)运行脚本,循环调用存储在外部介质的测试数据

  (4)验证所有测试结果是否符合期望的结果

  1.1使用TestNG进行数据驱动

  (1)打开百度首页

  (2)在搜索框中输入两个搜索关键词

  (3)单机搜索按钮

  (4)验证是否包含结果的关键字

  测试程序:

package cn.datadriven;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;

import java.util.concurrent.TimeUnit;

import javax.naming.directory.SearchResult;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;

public class DataProviderTest {
    private static WebDriver driver;
    //使用@DataProvider注解定义当前方法中的返回对象作为测试脚本的测试数据集,并且将测试数据集命名为“searchWords”
    @DataProvider(name = "searchWords")
    public static Object[][] words(){
        return new Object[][]{{"蝙蝠侠","主演","迈克尔"},{"超人","导演","扎克·施奈德"},{"生化危机","编剧","安德森"}};
    }
    
    //searchWord1和searchWord2为搜索时输入的值,SearchResult用来判断搜索结果是否包含该关键字
  @Test(dataProvider = "searchWords")
  public void test(String searchWord1,String searchWord2,String SearchResult) { 
      //等待10秒
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      driver.findElement(By.id("kw")).sendKeys(searchWord1+""+searchWord2);
      driver.findElement(By.id("su")).click();
      try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
      //判断页面中是否包含测试数据中所包含的关键字
      Assert.assertTrue(driver.getPageSource().contains(SearchResult));
  }
  @BeforeMethod
  public void beforeMethod() {
      System.setProperty("webdriver.chrome.driver", "D:\\WebDriver\\chromedriver_win32\\chromedriver.exe");
      driver = new ChromeDriver();
      driver.manage().window().maximize();
      driver.get( "https://www.baidu.com/");
  }

  @AfterMethod
  public void afterMethod() {
      driver.quit();
  }

}

 执行结果:

posted @ 2019-03-19 09:55  心生意动  阅读(172)  评论(0编辑  收藏  举报