调用库时Java中的空指针异常

时间:2016-07-14 09:09:17

标签: selenium

现在我修改了代码,但我仍然得到Null Pointer Exception

以下是我修改后的代码    在这里输入代码

package lib;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeMethod;
//@SuppressWarnings("unused")
public class Login {
WebDriver driver;
@BeforeMethod
void Initalisation()
{
System.setProperty("webdriver.ie.driver", "C:\\Eclipse\\IEDriverServer.exe");
    DesiredCapabilities capability=new DesiredCapabilities();
    capability.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
    InternetExplorerDriver driver=new InternetExplorerDriver(capability);
    driver.get("http://segotn11540.rds.volvo.com/vss_connect_testr1/Login/Login.aspx");

}

public Login(String UserName,String BrandName)
{

    driver.findElement(By.xpath("//input[@name='UserNameInputText']")).sendKeys(UserName);
    driver.findElement(By.xpath("//input[@name='Brand']")).sendKeys(BrandName);
    driver.findElement(By.xpath("//input[@name='CmdLogin']")).click();
    String Title=driver.getTitle();

    if(!Title.contains("VSS 4.0"))
            {
        System.out.println(UserName+""+"does not exists");
        driver.quit();
            }
    CheckForCancel();
}
private void CheckForCancel() {
    if(!driver.findElements(By.id("Cancel")).isEmpty())
    {
    driver.findElement(By.id("Cancel")).click();
    }

}

}

现在我将创建主Java文件

  

块引用   这将使用提供的参数启动登录

Import Login library
public class MessageBoard {
public static void main(String[] args)
{
    Login login=new Login("TYP40FI","Volvo");

}


}

以上代码有什么问题

3 个答案:

答案 0 :(得分:0)

尝试将驱动程序变量初始化为 WebDriver driver = new WebDriver();

答案 1 :(得分:0)

public Login(String UserName,String BrandName)

{

//Add this line in your code as you are trying in IE
driver = new InternetExplorerDriver();


driver.findElement(By.xpath("//input[@name='UserNameInputText']")).sendKeys(UserName);
driver.findElement(By.xpath("//input[@name='Brand']")).sendKeys(BrandName);
driver.findElement(By.xpath("//input[@name='CmdLogin']")).click();
String Title=driver.getTitle();

if(!Title.contains("VSS 4.0"))
        {
    System.out.println(UserName+""+"does not exists");
    driver.quit();
        }
CheckForCancel();

}

答案 2 :(得分:0)

  1. 调试和检查:是否在开始时调用Initalisation()
  2. 通常在测试开始前调用@BeforeMethod,因此@Test函数在哪里。 (语法可能有误)
  3. 如果你真的不关心@Test属性,那意味着你的Main函数需要在调用Initalisation()之前调用Login(...),否则驱动程序尚未设置(aka {{ 1}})