我在类sample中初始化了一个驱动程序对象。我想将驱动程序对象传递给其他类,但我得到一个空指针异常。我的代码是
示例类
public class sample {
WebDriver driver ;
@Test(priority=1)
public void openbrowser(){
System.setProperty("webdriver.chrome.driver",
"/home/ss4u/Desktop/Vignesh/jars/chromedriver");
driver = new ChromeDriver();
driver.get("http://www.google.com");
System.out.println(driver instanceof WebDriver);
}
@Test(priority=2)
public void maximize(){
driver.manage().window().maximize();
}
@Test(priority=3)
public void transfer_instance(){
sampleone obj=new sampleone(driver);
}
}
sampleclassone
public class sampleone {
WebDriver driver;
public sampleone(WebDriver driver){
this.driver=driver;
System.out.println(driver instanceof WebDriver);
System.out.println(this.driver instanceof WebDriver);
System.out.println("constructor2");
}
public sampleone(){
System.out.println("Default constructor called");
}
@Test(priority=1)
public void gettitle(){
System.out.println(this.driver instanceof WebDriver);
System.out.println(driver instanceof WebDriver);
String title=this.driver.getTitle();
System.out.println(this.driver instanceof WebDriver);
System.out.println(title);
Assert.assertEquals(title, "Google");
}
@Test(priority=2)
public void navigate(){
this.driver.get("https:in.yahoo.com");
}
}
Testng xml文件
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="TestNG" verbose="1" >
<test name="sample test">
<classes>
<class name="testsample.sample" />
</classes>
</test>
<test name="sample testone">
<classes>
<class name="testsample.sampleone" />
</classes>
</test>
</suite>
这个问题发生在iam调用类不使用创建的对象但是使用testng.xml文件有任何可能的方法来创建一个新的java实例(所有类通用)或使用所有类中的现有实例
答案 0 :(得分:4)
我自己找到了一个解决方案......当我详细阅读关于testng的文章时,我发现testng xml文件调用了xml文件中指定的所有类的默认构造函数。即使我们将对象传递给另一个类,我们也不能通过对象执行操作,因此发生空指针异常....我发现两个解决方案,第一个是使用pagefactory,第二个是使用公共驱动程序类为您的测试套件...所以我们可以使用相同的所有类中的驱动程序实例
常见的驱动程序类
public class Driver {
public static WebDriver driver=null;
public static WebDriver startdriver(String browser){
if(browser.equalsIgnoreCase("Chrome")){
System.setProperty("webdriver.chrome.driver", "/home/vicky/Documents/Jars/chromedriver");
driver=new ChromeDriver();
}else if(browser.equals("Firefox")){
driver=new FirefoxDriver();
}
return driver;
}
}
答案 1 :(得分:0)
使用与Java相同的extends关键字非常容易。只需要创建一个通用的webdriver类,您将在TestNG注释的帮助下打开所需的浏览器和应用程序URL,如下代码所示。
WebDriver Common Class:
public class Seleniumlinktext {
public WebDriver driver;
String baseurl = "http://www.google.co.in";
@BeforeTest
public void openBrowser(){
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
}
另一个班级:
public class WebDriverTest extends Seleniumlinktext {
@Test(priority=1)
public void linkText(){
//images hyperlink
driver.findElement(By.linkText("Images")).click();
System.out.println("Click on Images hyperlink");
}
就像这样,您可以将webdriver实例传递给所有其他clases。我从this site找到了解决方案。
这里我使用了@BeforeTest注释,因为在使用@Test注释开始执行测试用例之前,我的应用程序URL和浏览器应该只打开一次。