码迷,mamicode.com
首页 > 编程语言 > 详细

Selenium2(java)TestNG的使用 七

时间:2016-01-27 23:06:15      阅读:347      评论:0      收藏:0      [点我收藏+]

标签:

 

TestNG,即Testing Next Generation,下一代测试技术,是一套根据JUnit和NUnit思想而构建的利用注释来强化测试功能的一个测试框架,即可以用来做单元测试,也可以用来做集成测试。

安装:Help-->Install New Software

点击Add,在弹出的对话框输入:

技术分享

点击OK,一路安装即可

TestNG与selenium结合使用

  1. 新建Java项目selenium_testng_test
  2. 导入selenium和testng类库:项目右键-->Build Path-->Add Libraries分别添加selenium和testng类库
  3. 在src目录下新建一个包名:com.testng.test
  4. 新建一个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);
        }
    }
}

Selenium2(java)TestNG的使用 七

标签:

原文地址:http://www.cnblogs.com/sundalian/p/5164618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!