2013-02-27 54 views
0

当我从TestDriver类的主函数调用headerVerification方法时,虽然存在该元素,但我得到空指针异常。在函数isElementPresent中获取空指针异常在Selenium中...

启动服务器类:

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类

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

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

HeaderVerification.browser = browser; 

in StarstServer.startServer()方法。

+0

Benoit,非常感谢!有效 ... :) – Paras 2013-02-27 06:16:00