我需要实现一件事:每当我开始测试时,我都必须登录系统。我创建了一个应该运行此Login过程的类。我能够向这个类发送适当的值并且能够登录,但在那之后,我在我的第二个类(它自己运行测试)上接收到NullPointerException。它看起来根本无法看到浏览器窗口。请帮助我编写这个类,以便我可以在任意多个类中重复使用Login类。
登录之一:
public class Login {
private static WebDriver driver;
public static void Find_Fields (String path,String login, String password) {
driver = Driver.get(path);
WebElement login_field = driver.findElement(By.id("abc"));
login_field.sendKeys(login);
//Find Password Field on Start page
WebElement password_field = driver.findElement(By.id("abc"));
password_field.sendKeys(password);
//Find Login Button
WebElement login_button = driver.findElement(By.xpath("abc"));
login_button.click();
}
}
public class Testing {
private static WebDriver driver;
@BeforeClass
public static void a_setup(){
//here I'm trying to run Login with parameters
Login fields = new Login();
fields.Find_Fields(LOGIN_PATH, LOGIN, PASSWORD);
}
@Test
public void b_Press_Login_Button(){
//Here I'm trying to start testing in session started from a_setup()
WebElement keyword = driver.findElement("..."));
keyword.sendKeys("...");
}
@AfterClass
public static void Close(){
driver.quit();
driver.close();
}
}
答案 0 :(得分:1)
您需要使用浏览器对象初始化驱动程序。这样的事情应该有效:
public static void Find_Fields (String path,String login, String password)
{
driver = new FirefoxDriver();
driver.get(path);
WebElement login_field = driver.findElement(By.id("abc"));
login_field.sendKeys(login);
//Find Password Field on Start page
WebElement password_field = driver.findElement(By.id("abc"));
password_field.sendKeys(password);
//Find Login Button
WebElement login_button = driver.findElement(By.xpath("abc"));
login_button.click();
}
答案 1 :(得分:1)
您有两个独立的WebDriver字段,每个字段对应一个字段。您已经在Login中初始化了一个,但是您没有将引用传递回Testing类。其中一个解决方案是将WebDriver作为参数传递给Login构造函数:
public class Login {
private WebDriver driver;
public void Find_Fields (String path,String login, String password) {
driver.get(path);
//(...) rest of this method is unchanged
}
public Login(WebDriver driver) {
this.driver = driver;
}
}
public class Testing {
private static WebDriver driver;
@BeforeClass
public static void a_setup(){
driver = new FirefoxDriver(); //initialize the driver
Login fields = new Login(driver); //pass the instance of WebDriver to login class
fields.Find_Fields(LOGIN_PATH, LOGIN, PASSWORD);
}
//(...) rest of the class remains unchanged
}