尝试运行以下代码时,我收到Java Null指针异常。在Web页面甚至完全加载之前,测试就失败了。
我增加了页面加载超时和隐式等待时间,但是仍然无法正常工作。通过浏览器直接启动时,同一网页将在4秒内加载。请找到以下代码:
// Loginpagetest.java
Loginpage loginpage = new Loginpage();
public LoginPageTest() throws IOException {
super();
}
@BeforeMethod
public void setup(){
initialize();
}
@Test(priority=1)
public void loginPageTitleTest(){
String actualTitle = loginpage.validateLoginPageTitle();
String expectedTitle = "#1 Free CRM software in the cloud for sales and service";
Assert.assertEquals(actualTitle,expectedTitle);
}
// TestBase.java
public void initialize(){
String browsername = prop.getProperty("browser");
if(browsername.equals("chrome")){
System.setProperty("webdriver.chrome.driver","C:\\Users\\Pranaykumar\\Downloads\\"chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver(options);
}else if(browsername.equals("mozilla")){
System.setProperty("webdriver.gecko.driver","E:\\geckodriver.exe");
driver = new FirefoxDriver();
}
driver.manage().window().maximize();
//driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get(prop.getProperty("url"));
}
// Loginpage.java
public String validateLoginPageTitle(){
return driver.getTitle();
}
//控制台
[RemoteTestNG] detected TestNG version 6.14.3
Starting ChromeDriver 2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387) on port 42802
Only local connections are allowed.
[1548934220.587][WARNING]: Timed out connecting to Chrome, retrying...
Jan 31, 2019 5:00:25 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
FAILED: loginPageTitleTest
java.lang.NullPointerException
at com.crm.qa.pages.Loginpage.validateLoginPageTitle(Loginpage.java:37)
at com.crm.qa.testcases.LoginPageTest.loginPageTitleTest(LoginPageTest.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
答案 0 :(得分:0)
看起来这不是超时问题,它显示NullPointerException。驱动程序可能为空。 检查您的Chrome驱动程序路径是否正确。
‘FAILED:loginPageTitleTest java.lang.NullPointerException com.crm.qa.pages.Loginpage.validateLoginPageTitle(Loginpage.java:37)”
如果出现超时问题,则应该获取TimeoutExcepton。
答案 1 :(得分:0)
能否请您尝试在initialize()函数中以及driver.get(prop.getProperty("url"))
行之后显式等待特定对象,如下所示:
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(objectShouldPresent)));
答案 2 :(得分:0)
请在chromedriver_win32之前删除双引号(“)
System.setProperty("webdriver.chrome.driver","C:\\Users\\Pranaykumar\\Downloads\\"chromedriver_win32\\chromedriver.exe");
答案 3 :(得分:-1)
可能的情况是,您正在Loginpage
页面对象内创建驱动程序的新实例,而不是传递现有实例,因此该实例不会被初始化...因此是NPE。