在Selenium中获取函数isElementPresent的Null指针异常...

时间:2013-02-27 05:20:33

标签: java selenium-rc

当我从TestDriver类的main函数调用headerVerification方法时,我得到空指针异常,尽管元素存在。

启动服务器类:

package WebTesting;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class StartServer {

    private String host;
    private String nameOfBrowser;
    private int port;
    private String url;

    public StartServer(String host, int port, String nameOfBrowser, String url){
        this.host=host;
        this.port=port;
        this.nameOfBrowser=nameOfBrowser;
        this.url=url;
    }

    public static Selenium browser;

    public void startServer(){
        browser = new DefaultSelenium(host, port, nameOfBrowser, url);
        browser.start();
        browser.open("/");
        System.out.println("Browser Started !!!");
    }
}

标头验证类

package WebTesting;

import com.thoughtworks.selenium.Selenium;

public class HeaderVerification {

    private String elementPath;
    private String linkPath;
    private String testLink;

    public HeaderVerification(String elementPath, String linkPath, String testLink){
        this.elementPath=elementPath;
        this.linkPath=linkPath;
        this.testLink=testLink;
    }

    public static Selenium browser;

    public void headerVerification() throws InterruptedException{
        System.out.println(elementPath);
        if(browser.isElementPresent(elementPath)){
            Thread.sleep(5000);
            System.out.println("Header is Present");
            browser.click(linkPath);
            Thread.sleep(5000);

            if(browser.getLocation().equals(testLink)){
                System.out.println("Correct Location!!!");
            }
            else
                System.out.println("Incorrect Location!!!");

            browser.close();
            System.out.println("Browser Closed!!!");
        }
    }
}

TestDriver Class

package WebTesting;

public class TestDriver {

    /**
     * @param args
     */

    static StartServer ss = new StartServer("localhost", 4444, "*firefox", "http://docs.seleniumhq.org/");
    static HeaderVerification hv = new HeaderVerification ("//div[@id='header']", "//a[@title='Overview of Selenium']", "http://docs.seleniumhq.org/about/");

    public static void main(String[] args) throws InterruptedException {
         // TODO Auto-generated method stub
         ss.startServer();
         hv.headerVerification();

    }

}

1 个答案:

答案 0 :(得分:1)

null类中的浏览器静态变量为HeaderVerification。你应该添加

HeaderVerification.browser = browser;

StarstServer.startServer()方法中。