2017-02-12 177 views
0

我附加了POM,BaseTest和Test類。我爲下面的代碼嘗試通過右鍵單擊項目來運行它作爲TestNG測試而獲得NullPointerException。請提出建議?嘗試使用PageFactory運行我的腳本時出現「NullPointerException」

POM類:

package pom; 

import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.support.FindBy; 
import org.openqa.selenium.support.PageFactory; 

public class Introduction 
{ 

@FindBy(xpath="//a[text()='Hello. Sign In']") 
WebElement signInLink; 

public Introduction(WebDriver driver) 
{ 
PageFactory.initElements(driver, this); 
} 

public void signIn() 
{ 
    signInLink.click(); 
} 
} 

BaseTest類:

package scripts; 

import java.util.concurrent.TimeUnit; 

import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.testng.annotations.*; 


public class BaseTest 
{ 
public WebDriver driver; 

@BeforeSuite 
public void preCondition() 
{ 
    driver= new FirefoxDriver(); 
    driver.get("https://www.walmart.com/"); 
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 
} 

@AfterSuite 
public void postCondition() 
{ 
    driver.close(); 
} 
} 

測試類:

package scripts; 

import org.testng.annotations.Test; 

import pom.Introduction; 

public class SignIn extends BaseTest 
{ 

@Test 

public void validSignIn() 
{ 
    Introduction i= new Introduction(driver); 
    i.signIn(); 
} 
} 
+0

嘗試增加超時?你看到正確加載的頁面嗎? – liquide

+0

你能分享異常跟蹤嗎? – Mahipal

回答

0

代碼有幾個問題。

  • 您正在初始化您的webdriver在@BeforeSuite。這會導致您的webdriver實例僅根據<suite>標記創建一次。所以所有其他@Test方法將始終得到NullPointerException,因爲@BeforeSuite註釋的方法不會再次執行。
  • 您正在訴諸使用隱式超時。請不要使用隱式超時。您可以在this SO帖子中閱讀更多關於隱性等待的禍害。

所以上手,我建議改變你的測試代碼類似下面

BaseTest.java

package scripts; 

import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.testng.annotations.*; 

public class BaseTest { 
    private static ThreadLocal<WebDriver> driver = new ThreadLocal<>(); 

    @BeforeMethod 
    public void preCondition() { 
     driver.set(new FirefoxDriver()); 
     driver.get().get("https://www.walmart.com/"); 
    } 

    @AfterMethod 
    public void postCondition() { 
     driver.get().quit(); 
    } 

    public final WebDriver driver() { 
     return driver.get(); 
    } 
} 

SignIn.java

package scripts; 

import org.testng.annotations.Test; 

import pom.Introduction; 

public class SignIn extends BaseTest { 

@Test 
public void validSignIn() { 
    Introduction i = new Introduction(driver()); 
    i.signIn(); 
} 
} 

這裏我們所做的是選擇使用@BeforeMethod@AfterMethod用於實例化和清理webdriver,因爲這些方法保證在每個@Test方法之前和之後執行。然後,我們繼續使用ThreadLocalWebdriver的變體,因爲ThreadLocal確保每個線程都獲得自己的webdriver副本,以便您可以輕鬆地開始並行運行測試。這現在不是問題,但是當你開始構建你的實現時,你很快就會面臨這個問題。您可以通過閱讀我的this blog文章瞭解更多關於如何使用TestNG進行並行執行的信息。

相關問題