问题描述:

There are several tests with different test groups. And I'm trying to run each of them with different set of data by using @DataProvider with ITestContext inside. I get NullPointerException. Here is my code:

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;

}

网友答案:
  • If you directly run your testng class, it will first call dataprovider which cant get groups information as groups are not available. But instead if you call this class via testng.xml, it will have groups info available with ITestContext.

  • You need to call this class(class name is say 'ParameterByITestContextInDataprovider') through TestNG xml.

Below is sample 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>
相关阅读:
Top