我在POM selenium webdriver中遇到了一个问题。这是我的一个类的代码。
package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class KnowledgeBase {
private static WebDriver driver = null;
public void opening_correlation_explorer()
{
driver.findElement(By.xpath("//*[@id='warren-nav']/div[2]/ul/li[3]/a")).click();
driver.findElement(By.xpath("//*[@id='warren-nav']/div[2]/ul/li[3]/ul/li[1]/a")).click();
}
这是我的另一个类的代码:
package Pages;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class LoginPage {
private static WebDriver driver = null;
public void login()
{
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
driver.get("https://www.website.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement loginButton = driver.findElement(By.xpath("/html/body/nav/div/a[7]"));
loginButton.click();
WebElement Email = driver.findElement(By.xpath("//*[@id='loginform']/div[2]/div[1]/div[1]/input[1]"));
Email.sendKeys("abc@gmail.com");
WebElement Password = driver.findElement(By.xpath("//*[@id='loginform']/div[2]/div[1]/div[1]/input[2]"));
Password.sendKeys("123456");
WebElement signin_button = driver.findElement(By.xpath("//*[@id='login']"));
signin_button.click();
}
}
我正在运行一个测试用例,用户登录(从类LoginPage),然后重定向到新页面(从类KnowledgeBase)。测试用例类如下:
package TestCases;
import Pages.KnowledgeBase;
import Pages.LoginPage;
public class correlation_explorer {
public static void main(String[] args) {
// TODO Auto-generated method stub
LoginPage user_login = new LoginPage();
KnowledgeBase correlation = new KnowledgeBase();
user_login.login();
correlation.opening_correlation_explorer();
}
}
在这个测试用例类中,我创建了两个类的两个对象,我必须从中调用方法,但是当我运行此测试时,只运行LoginPage类测试。之后它给了我以下例外。
Exception in thread "main" java.lang.NullPointerException
at Pages.KnowledgeBase.opening_correlation_explorer(KnowledgeBase.java:20)
at TestCases.correlation_explorer.main(correlation_explorer.java:18)
任何帮助都将受到高度赞赏。
答案 0 :(得分:1)
我没有注意到
中驱动程序的任何初始化public class KnowledgeBase {
private static WebDriver driver = null;
因此NullPointer意味着您在KnowledgeBase中的驱动程序为空。我建议你
代码如下
public static void main(String[] args) {
Webdriver driver = new ChromDriver();
//Here I suggest you pass driver to every page Object as their Constructor parameter.
LoginPage user_login = new LoginPage(driver);
//in login() method you must return a new KnowledgeBase(driver).
KnowledgeBase correlation = user_login.login();
correlation.opening_correlation_explorer();
}