我创建了2个包,每个包含一个java类文件。第一个包中的Utility类启动驱动程序&使用方法launchDriver()
&关闭驱动程序closeDriver()
。在第二个包中 - 示例java类文件包含对这些方法的调用。使用launchDriver()
成功启动驱动程序但是当驱动程序传递给closeDriver
方法时,该值变为null ...
请提供解决方案。代码如图所示..
public class Utility {
public static WebDriver driver;
public static String driverpath="E:\\Drivers";
@Test
public static WebDriver launchDriver(final String browser,final String url){
if(browser=="firefox"){
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get(url);
}else if(browser=="chrome"){
System.setProperty("webdriver.chrome.driver", driverpath+"\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
}else if(browser=="ie"){
System.setProperty("webdriver.ie.driver", driverpath+"\\IEDriverServer.exe");
WebDriver driver=new InternetExplorerDriver();
driver.manage().window().maximize();
driver.get(url);
}else{
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get(url);
}
return driver;
}
@Test
public static WebDriver closeDriver(WebDriver driver){
Utility.driver=driver;
driver.quit();
return driver;
}
}
类测试包中的示例
public class Example{
@Test
public static void launchConfig(){
Utility.launchDriver("chrome", "https://www.google.com");
//Utility.launchDriver("firefox","www.google.com");
Utility.closeDriver(Utility.driver);
}
}
答案 0 :(得分:0)
创建一个抽象测试类,让测试类扩展它。您的抽象测试类可能如下所示:
public abstract class Abstract test {
//delcare driver
public static WebDriver driver;
//Assign the correct driver
@BeforeSuite
public void webdriverSetUp() {
if(browser=="firefox"){
WebDriver driver=new FirefoxDriver();
} else if(browser=="chrome"){
WebDriver driver=new ChromeDriver();
} else if(browser=="ie"){
WebDriver driver=new InternetExplorerDriver();
} else{
WebDriver driver=new FirefoxDriver();
}
}
//call getDriver() in your tests
public static WebDriver getDriver() {
return driver;
}
}
不要忘记你可能想要清除测试方法之间的所有cookie。