Selenium webdriver 将驱动程序实例传递给另一个具有构造函数的类

Selenium webdriver 将驱动程序实例传递给另一个具有构造函数的类,selenium-webdriver,Selenium Webdriver,我正在将一个WebDriver实例作为 FunctionalComponents fc = new FunctionalComponents(driver) 来自另一个类,但对象创建发生在构造函数执行之前。实际上,创建的对象在驱动程序实例中具有null值 我怎样才能解决这个问题 public class FunctionalComponents { public FunctionalComponents(WebDriver driver) { th

我正在将一个
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
    }
}

在字段定义期间,不要在外部设置成员变量的值。从构造函数中执行,这将保证变量的填充符合您的要求。也就是说:

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
    }
}

在字段定义期间,不要在外部设置成员变量的值。从构造函数中执行,这将保证变量的填充符合您的要求。也就是说:

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
    }
}

嘿,Jim,您还没有在FunctionalComponents类中声明
驱动程序
实例。我想你是想添加
私有WebDriver?否则,此驱动程序将失败。。。嗯,它不会编译,但你知道我的意思。出于同样的原因,原始海报的代码也不会编译。:)当然,你是对的,但我只是想演示一下解决方案。编辑了修复的答案。嘿,Jim,你还没有在FunctionalComponents类中声明
驱动程序
实例。我想你是想添加
私有WebDriver?否则,此驱动程序将失败。。。嗯,它不会编译,但你知道我的意思。出于同样的原因,原始海报的代码也不会编译。:)当然,你是对的,但我只是想演示一下解决方案。编辑了要修复的答案。