我有一个在类示例中初始化的驱动程序对象。我也想将驱动程序对象传递给其他类,但我得到一个空指针异常。我的代码是
样本类
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);
}
}
样本类一
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");
}
}
测试 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 实例(对所有类通用)或使用所有类中的现有实例
我自己找到了一个解决方案...当我详细阅读 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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)