我正在使用带有Selenium的TestNG。我正在尝试使用driver.getWindowHandle((;在弹出窗口、iframe等之间切换。
问题是,如果我在TNGDriver类中这样声明
public String originalHandle = driver.getWindowHandle();
我得到一个java.lang.NullPointerException(很明显,因为这是在驱动程序之前初始化的(。如何声明一次并开始在其他类中使用它?请记住,我的类是在它们之间扩展的,我需要在其他类的方法中使用这个originalHandle变量,例如:
public void clickOnFacebookIcon() {
Assert.assertTrue(true, driver.findElement(By.id(FACEBOOK_ICON)).getText());
driver.findElement(By.id(FACEBOOK_ICON)).click();
for(String handle : driver.getWindowHandles()) {
if (!handle.equals(originalHandle)) {
driver.switchTo().window(handle);
driver.close();
}
}
driver.switchTo().window(originalHandle);
}
这是我的其他课程:
TNGDriver类
public class TNGDriver {
public static WebDriver driver;
public static final String CHROME_DRIVER_PATH = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe";
private WebDriverWait wait;
@SuppressWarnings("deprecation")
public void init() {
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
System.setProperty("webdriver.chrome.driver", CHROME_DRIVER_PATH);
driver = new ChromeDriver(capabilities);
driver.manage().window().maximize();
}
public WebDriverWait getWait() {
wait = new WebDriverWait(driver, 60);
return wait;
}
测试用例1类
public class Testcase1 extends Registration {
TNGDriver tngDriver = new TNGDriver();
@BeforeTest
public void setup() {
tngDriver.init();
}
@Test(priority = 1)
public void step1_clickOnSignIn() {
clickOnSignIn();
}
@Test(priority = 2)
public void step2_clickOnFacebookIcon() {
clickOnFacebookIcon();
}
您可以使用设计模式来完成
https://en.wikipedia.org/wiki/Singleton_pattern
使用此模式,您将只拥有对象的一个实例。
class Singleton
{
// static variable single_instance of type Singleton
private static Singleton single_instance = null;
// variable of type String
public String originalHandle = driver.getWindowHandle();
// private constructor restricted to this class itself
private Singleton()
{
//Do something on constructor
}
// static method to create instance of Singleton class
public static Singleton getInstance()
{
if (single_instance == null)
single_instance = new Singleton();
return single_instance;
}
}
要访问它,您可以执行类似于的操作
Singleton x = Singleton.getInstance();
//To access the String variable
x.s