selenium2中TestNG相关解释

testNg官网:http://testng.org/doc/documentation-main.html

新建testNG class的时候,同时也新建了一个TestNG.xml的文件。

  此xml文件定义了一个测试套件(suite),name属性定义了这个测试套件的名字,这个name会在测试报告中引用。parallel并行执行方式为false,也就是说这个起不了作用。parallel值有多种,可以是classes,tests,methods和false等。TestNG允许以并行,即多线程的方式来执行测试。这就意味着基于TestNG测试组件的配置,多个线程可以被同时启动,然后分别执行各自的测试方法。相对于传统的单线程执行测试的方法,这种多线程方式拥有很大的优势,主要是可以减少测试运行时间,并且可以验证某段代码在多线程环境中运行的正确性。

<test name="Test">

  suite中又有一个test,其中name属性是这个测试用例的名字,可以自己定义。

<classes>
<class name="com.demo.test.NewTest"/>
</classes>

  定义了要执行测试的类。在Eclipse中选中该文件并且以TestNG测试套件方式运行它。

刷新selenium_tesng_demo项目,你会发现通过配置文件执行的测试会在项目目录下生成一个文件夹:test-ouput这是就是存储报告的目录,我们打开目录下的emailable-report.html文件,如图:

其中Test和Suite这两个名字都尅根据具体功能来命名。

<suite name="Suite" parallel="false">
<test name="Test">

 NewTest.java文件代码:

package com.demo.test;

import java.util.concurrent.TimeUnit;

import org.junit.Assert;
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.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class NewTest {
    private WebDriver driver;

    @Test
    public void f() {
        By inputBox = By.id("kw");
        By searchButton = By.id("su");

        // 智能等待元素加载完成
        intelligentWait(driver, 10, inputBox);
        intelligentWait(driver, 10, searchButton);

        driver.findElement(inputBox).sendKeys("java");
        driver.findElement(searchButton).click();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @BeforeTest
    public void beforeTest() {
        driver = new FirefoxDriver();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("https://baidu.com");
    }

    @AfterTest
    public void afterTest() {
        driver.quit();
    }

    public void intelligentWait(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 + "]");
        }
    }
}

关于TestNG注释的详细解释,可查看:http://www.cnblogs.com/yajing-zh/p/4925155.html

原文地址:https://www.cnblogs.com/yajing-zh/p/5077758.html