尝试运行测试用例时,selenium中线程“main”java.lang.NullPointerException中的异常

时间:2015-01-02 15:19:03

标签: selenium webdriver

以下是我的简单测试用例程序:

    package mypackage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class myclass {

    public WebDriver driver;
    public static void main(String[] args) {
        myclass dr= new myclass();
        dr.start();
        dr.select();
    }

    public void start(){

        WebDriver driver= new FirefoxDriver();
        driver.get("https://www.google.co.in/");
    }

    public void select(){
        driver.findElement(By.linkText("Gmail")).click();
    }

}

但每次运行时都会抛出以下错误:

    Exception in thread "main" java.lang.NullPointerException
    at mypackage.myclass.select(myclass.java:26)
    at mypackage.myclass.main(myclass.java:15)

浏览器启动并显示谷歌主页,但选择gmail链接的下一步操作没有发生,并且出现错误。 **在不同的浏览器(即chrome)上尝试过此操作,但错误仍然存​​在

请帮助我,我是硒的新手..

1 个答案:

答案 0 :(得分:0)

只需从上面已经声明的start()方法中删除“WebDriver”实例,如果使用它,那么“WebDriver”全局声明不在方法start()的当前范围内

 package mypackage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class myclass {

    public WebDriver driver;
    public static void main(String[] args) {
        myclass dr= new myclass();
        dr.start();
        dr.select();
    }

    public void start(){

        driver= new FirefoxDriver();
        driver.get("https://www.google.co.in/");
    }

    public void select(){
        driver.findElement(By.linkText("Gmail")).click();
    }

}