TestNG,ITestContext - getIncludedGroups返回Null

时间:2015-06-30 06:06:08

标签: java selenium-webdriver testng testng-dataprovider

有几个不同测试组的测试。我尝试使用内置ITestContext的@DataProvider来尝试使用不同的数据集运行每个数据。我得到NullPointerException。这是我的代码:

String url = "http://google.com";
FirefoxDriver driver = new FirefoxDriver();

@BeforeTest(groups={"A","B"})
public void launchOfBrowser(){
    driver.get(url);
}

@Test(dataProvider="Search", groups="A")
public void searchByUser(String author, String key) throws InterruptedException{
    System.out.println("Welcome " + author + ", your search value is: " + key);
    String enteredValue;
    driver.findElement(By.name("q")).sendKeys(key);
    Thread.sleep(3000);
    enteredValue = driver.findElement(By.name("q")).getAttribute("value");
    Assert.assertEquals(enteredValue, key);
    driver.findElement(By.name("q")).clear();
}

@Test(dataProvider="Search", groups="B")
public void searchByIncognito(String key) throws InterruptedException{
    System.out.println("Your search value is: " + key);
    String enteredValue;
    driver.findElement(By.name("q")).sendKeys(key);
    Thread.sleep(3000);
    enteredValue = driver.findElement(By.name("q")).getAttribute("value");
    Assert.assertEquals(enteredValue, key);
    driver.findElement(By.name("q")).clear();
}

@AfterTest(groups={"A","B"})
public void closeSessions(){
    driver.quit();
}

@DataProvider(name="Search")
public static Object[][] getDataFromDataprovider(ITestContext c){

    Object[][] groupArray = null;

    for(String group : c.getIncludedGroups()){
        if (group.equalsIgnoreCase("A")){
            groupArray =  new Object[][] {
                { "Guru99", "India" },
                { "Krishna", "UK" },
                { "Bhupesh", "USA" }
            };
        }
        else{
            groupArray =  new Object[][] {
                { "India" },
                { "UK" },
                { "USA" }
            };
        }   
    }
    return groupArray;
}

1 个答案:

答案 0 :(得分:4)

  • 如果您直接运行您的testng类,它将首先调用dataprovider,由于组不可用,因此无法获取组信息。但是,如果您通过testng.xml调用此类,它将具有ITestContext可用的组信息。

  • 您需要通过TestNG xml调用此类(类名称为'ParameterByITestContextInDataprovider')。

以下是xml示例: -

<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="test-parameter">

  <test name="example1">

    <groups>
        <run>
            <include name="A" />
        </run>
    </groups>

    <classes>
       <class
        name="com.package123.ParameterByITestContextInDataprovider" />
    </classes>

  </test>


  <test name="example2">

    <groups>
        <run>
            <include name="B" />
        </run>
    </groups>

    <classes>
       <class
        name="com.package123.ParameterByITestContextInDataprovider" />
    </classes>

  </test>

</suite>