2016-11-23 50 views
0

我是JAVA和Selenium的新手,我真的很想理解爲什麼我的代碼不起作用並拋出NullPointerException。NullPointerException當使用一個對象來調用具有Selenium WebDriver代碼的方法

基本上,我想要做的是調用WebDriver實現從不同類到「主測試」類的方法,該類將作爲JUnit測試執行。

但每次我執行我的主測試,然後引發NullPointerException。

這裏是我的主測試將被執行:

package common_methods; 

import org.junit.*; 

public class Master_Test extends Configurations { 

    @Before 
    public void setUp(){ 
     try{ 
     testConfiguration(); 
     driver.get("http://only-testing-blog.blogspot.ro/"); 
     } catch (Exception e){ 
      System.out.println("setUp Exception: "+e); 
     } 
    } 

    @After 
    public void tearDown(){ 
     driver.close(); 
    } 

    @Test 
    public void masterTest(){ 
     try{ 
     TestCase1 testy1 = new TestCase1(); 
     testy1.test1(); 
     }catch (Exception master_e){ 
      System.out.println("Test Exception: "+master_e); 
     } 
    } 
} 

現在更好地理解這裏是正在擴展的配置類:

package common_methods; 

import org.openqa.selenium.*; 
import org.openqa.selenium.chrome.ChromeDriver; 

public class Configurations { 

    public WebDriver driver; 

    public void testConfiguration() throws Exception{ 
     System.setProperty("webdriver.chrome.driver", "D:\\Browser_drivers\\chromedriver_win32\\chromedriver.exe"); 
     driver = new ChromeDriver(); 
    } 
} 

這裏是TestCase1類從中我得到我的方法:

package common_methods; 

import org.openqa.selenium.*; 

public class TestCase1 extends Configurations{ 

    public void test1() throws Exception{ 
     driver.findElement(By.id("tooltip-1")).sendKeys("Test Case 1 action"); 
     Thread.sleep(5000); 
    } 
} 

爲什麼我會得到NullPointerException?

回答

0

在Master_Test,你在哪裏調用

TestCase1 testy1 = new TestCase1(); 

你需要通過驅動程序的參考,因此它不會給NullPointerException異常。另外,您需要在TestCase1類中添加一個構造函數來處理驅動程序。

檢查下面的代碼。我曾與FirefoxDriver &谷歌使用它 -

import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver; 

public class Configurations { 

    public WebDriver driver; 

    public void testConfiguration() { 
     driver = new FirefoxDriver(); 
    } 
} 

Master_Test

import org.junit.Before; 
import org.junit.Test; 
import org.openqa.selenium.WebDriver; 



public class Master_Test extends Configurations { 

    @Before 
    public void setUP() { 
     testConfiguration(); 
     driver.get("http://www.google.com"); 
    } 

    @Test 
    public void masterTest() { 
     TestCase1 test = new TestCase1(driver); 
     test.test1(); 
    } 
} 

TestCase1

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 

public class TestCase1 extends Configurations { 

    public TestCase1(WebDriver driver) { 
     this.driver = driver; 
    } 

    public void test1() { 
     driver.findElement(By.id("lst-ib")).sendKeys("test"); 
    } 
} 
+0

感謝阿尼什!它的工作原理,我明白爲什麼它沒有工作:) –

相關問題