2017-10-21 32 views
0

我傳遞一個WebDriver實例類以下爲傳遞驅動程序實例到另一個類的構造函數

FunctionalComponents fc = new FunctionalComponents(driver) 

從另一個類,但在執行構造函數之前創建對象發生。實際上,創建的對象在驅動程序實例中具有null值。

我該如何解決這個問題?

public class FunctionalComponents 
{  
    public FunctionalComponents(WebDriver driver) 
    { 
     this.driver = driver;        
    } 

    CaptureElement element= new CaptureElement(driver); 

    public void Method() 
    { 
     // method logic 
     // i call object element here 
    } 
} 

回答

2

在字段定義期間,不要在外面設置成員變量的值。在構造函數內部執行,這將保證變量的數量隨你喜歡。如果:

public class FunctionalComponents 
{ 
    private IWebDriver driver; 
    private CaptureElement element; 

    public FunctionalComponents(WebDriver driver) 
    { 
     this.driver = driver; 
     this.element = new CaptureElement(driver); 
    } 

    public void Method() 
    { 
     // method logic 
     // i call object element here 
    } 
} 
+1

嗨,吉姆,你還沒有在FunctionalComponents類中聲明'driver'實例。我想你想添加'私人WebDriver驅動程序;'?否則,'this.driver'會失敗......它不會編譯,但你知道我的意思。 – JeffC

+1

原始海報的代碼也不會出於同樣的原因。 :)當然,你是對的,但我真的只是試圖展示解決方案。編輯答案來解決。 – JimEvans

相關問題