使用构造函数将驱动程序实例传递给另一个类

时间:2017-10-21 15:45:48

标签: selenium-webdriver

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

1 个答案:

答案 0 :(得分: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
    }
}
相关问题