TestNG,即Testing Next Generation,下一代测试技术,是一套根据JUnit和NUnit思想而构建的利用注释来强化测试功能的一个测试框架,即可以用来做单元测试,也可以用来做集成测试。
安装:Help-->Install New Software
点击Add,在弹出的对话框输入:
点击OK,一路安装即可
TestNG与selenium结合使用
- 新建Java项目selenium_testng_test
- 导入selenium和testng类库:项目右键-->Build Path-->Add Libraries分别添加selenium和testng类库
- 在src目录下新建一个包名:com.testng.test
- 新建一个TestNG测试类,命名NewTest
实现代码:
package com.testng.test; import org.testng.annotations.Test; import org.testng.annotations.BeforeTest; import org.testng.annotations.AfterTest; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; public class NewTest { //声明一个全局变量driver private WebDriver driver; @Test public void f() { By inputBox = By.id("kw"); By searchButton = By.id("su"); intelligenWait(driver, 10, inputBox); intelligenWait(driver, 10, searchButton); driver.findElement(inputBox).sendKeys("JAVA"); driver.findElement(searchButton).click(); try { Thread.sleep(2000); } catch(InterruptedException e){ e.printStackTrace(); } } @BeforeTest public void beforeTest() { driver = new FirefoxDriver(); driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get("http://www.baidu.com"); } @AfterTest public void afterTest() { driver.quit(); } /**这是智能等待元素加载的方法**/ public void intelligenWait(WebDriver driver, int timeOut, final By by) { try { (new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>(){ public Boolean apply(WebDriver driver) { WebElement element = driver.findElement(by); return element.isDisplayed(); } }); } catch (TimeoutException e) { Assert.fail("超时!" + timeOut + "秒之后还没有找到元素[" + by + "]", e); } } }