该文章主要介绍 testNG(testing next generation,下一代测试技术)框架的使用。
1.首先安装testNG
2.安装完成后,创建maven项目,导入TESTNG和selenium依赖。
3.此时就可以直接创建testNG的测试类了
4.下面通过 百度页面打开、输入关键字、进行搜索,来简单演示一下testNG的使用
1 package testNGSelenium.testNGDemo; 2 3 import org.testng.annotations.Test; 4 import org.testng.annotations.BeforeTest; 5 import org.testng.annotations.DataProvider; 6 import org.testng.annotations.Parameters; 7 8 import java.util.Date; 9 import java.util.concurrent.TimeUnit; 10 11 import org.apache.bcel.generic.NEW; 12 import org.apache.commons.collections.map.StaticBucketMap; 13 import org.openqa.selenium.By; 14 import org.openqa.selenium.WebDriver; 15 import org.openqa.selenium.WebElement; 16 import org.openqa.selenium.chrome.ChromeDriver; 17 import org.openqa.selenium.support.ui.ExpectedCondition; 18 import org.openqa.selenium.support.ui.WebDriverWait; 19 import org.testng.annotations.AfterTest; 20 21 public class NewTest { 22 //声明一个全局变量 23 private WebDriver driver; 24 25 26 27 @Test 28 @Parameters({"keyWord"}) 29 public void f(String keywords) { 30 final By input1 = By.id("kw"); 31 final By button1 = By.id("su"); 32 33 //智能等待页面的输入框加载出来 34 try { 35 36 (new WebDriverWait(driver, 3)).until(new ExpectedCondition<Boolean>() { 37 38 public Boolean apply(WebDriver input) { 39 WebElement element = input.findElement(input1); 40 System.out.println(new Date()); 41 return element!= null; 42 } 43 }); 44 45 } catch (Exception e) { 46 System.out.println("输入框3S还没加载出来!!!"); 47 e.printStackTrace(); 48 } 49 50 51 //智能等待页面的搜索按钮加载出来 52 try { 53 (new WebDriverWait(driver, 3)).until(new ExpectedCondition<Boolean>() { 54 55 public Boolean apply(WebDriver input) { 56 WebElement element = input.findElement(button1); 57 System.out.println(new Date()); 58 return element!= null; 59 } 60 }); 61 } catch (Exception e) { 62 System.out.println("搜索按钮等待了3秒还未加载出来"); 63 e.printStackTrace(); 64 } 65 66 67 driver.findElement(input1).sendKeys(keywords); 68 driver.findElement(button1).click(); 69 70 //等待10S,便于观察结果 71 try { 72 Thread.sleep(10000); 73 } catch (InterruptedException e) { 74 75 e.printStackTrace(); 76 } 77 78 79 } 80 @BeforeTest 81 public void beforeTest() { 82 driver = new ChromeDriver(); 83 //窗口最大化 84 driver.manage().window().maximize(); 85 86 //加载页面 87 driver.get("http://www.baidu.com"); 88 89 //设置页面完全加载时间为3秒,第二个参数TimeUnit.SECONDS是指定时间单位 90 driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS); 91 92 } 93 94 @AfterTest 95 public void afterTest() { 96 driver.quit(); 97 } 98 99 }