【问题标题】:Passing driver instance to another class with constructor使用构造函数将驱动程序实例传递给另一个类
【发布时间】:2017-10-21 15:45:48
【问题描述】:

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

【问题讨论】:

    标签: selenium-webdriver


    【解决方案1】:

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

    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 类中声明 driver 实例。我想你的意思是添加private WebDriver driver;?否则this.driver 将会失败......好吧它不会编译但你知道我的意思。
    • 出于同样的原因,原始发帖人的代码也不会。 :) 当然,你是对的,但我真的只是想演示解决方案。修改答案以修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多