getWindowHandle()引发错误消息“ NullpointerException”

时间:2019-08-15 20:38:17

标签: selenium

这是一个简单的硒函数,正在尝试获取窗口句柄。

在该声明中,它会抛出“ Nullpointerexception”

Error

import static org.junit.Assert.*;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class WindowHandles {
	WebDriver achromeDriver;
	String abaseUrl;	

	
	public void setUp() throws Exception {
		
		abaseUrl = "http://letskodeit.teachable.com/pages/practice";
		
		System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\ChromeDirver\\chromedriver.exe");
		
		achromeDriver = new ChromeDriver();
		
		achromeDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		
		achromeDriver.manage().window().maximize();;		
		
		System.out.println("setup completed");
	}
	
	@Test
	public void test() {
		
		try{
			
			String aparentwindowHandle = achromeDriver.getWindowHandle();
			
			System.out.println("the parent window handle is "+ aparentwindowHandle);
			
			WebElement aopenwindowelementbutton = achromeDriver.findElement(By.id("openwindow"));
		
			aopenwindowelementbutton.click();
			
			String achildwindowhandle = achromeDriver.getWindowHandle();
			
			System.out.println("the child window handle is: " + achildwindowhandle);
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		
				
		
	}

}

1 个答案:

答案 0 :(得分:-1)

有关用例和观察的更多详细信息将有助于我们以更好的方式调试问题。但是,似乎您正在使用junit框架,并且缺少任何注释都不会执行 setUp() 方法。

由于test()方法带有@Test注释,因此程序以achromeDriver到达 Null


解决方案

一种快速的解决方案是将@Before注释添加到setUp()方法中,如下所示:

@Before
public void setUp() throws Exception {

    abaseUrl = "http://letskodeit.teachable.com/pages/practice";
    System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\ChromeDirver\\chromedriver.exe");
    achromeDriver = new ChromeDriver();
    achromeDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    achromeDriver.manage().window().maximize();;        
    System.out.println("setup completed");
}