【问题标题】:Initialize webdriver inside BeforeFeature method在 BeforeFeature 方法中初始化 webdriver
【发布时间】:2021-04-24 00:02:29
【问题描述】:

我有以下问题。我需要使用上下文注入在 specflow BeforeFeature 方法中注册我的 webdriver 实例,但此方法必须是静态的。我有一个错误,我的全局容器对象必须是静态的。有没有办法在静态方法中使用这种上下文注入?

这是我的代码:

[Binding]
public class SpecflowHooks
{
    private readonly IObjectContainer container;

    public SpecflowHooks(IObjectContainer container)
    {
        this.container = container;
    }

    [BeforeFeature]
    public static void OneTime()
    {
        ChromeOptions options = new ChromeOptions();
        options.AddArgument("--ignore-ssl-errors=yes");
        options.AddArgument("--ignore-certificate-errors");
        ChromeDriver driver = new ChromeDriver();
        driver.Manage().Window.Maximize();
        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);

        container.RegisterInstanceAs<IWebDriver>(driver);
    }

    [BeforeScenario]
    public void SetUp()
    {

    }

    [AfterScenario]
    public void TearDown()
    {

    }

    [AfterFeature]
    public static void FeatureTearDown()
    {
        IWebDriver driver = container.Resolve<IWebDriver>();

        driver.Close();
        driver.Dispose();
    }
}

【问题讨论】:

    标签: c# selenium specflow


    【解决方案1】:

    我假设您只想为每个功能初始化一次 Web 驱动程序,并为功能中的每个场景重用现有的 Web 驱动程序对象。

    如您所述,BeforeFeature 挂钩是静态的。您仍然可以使用它来初始化 Web 驱动程序,但将其分配给 hooks 类的静态字段。然后在 BeforeScenario 中,将静态 Web 驱动程序对象注册到依赖注入容器中:

    [Binding]
    public class SpecflowHooks
    {
        private static IWebDriver driver;
        private readonly IObjectContainer container;
    
        public SpecflowHooks(IObjectContainer container)
        {
            this.container = container;
        }
    
        [BeforeFeature]
        public static void OneTime()
        {
            ChromeOptions options = new ChromeOptions();
            options.AddArgument("--ignore-ssl-errors=yes");
            options.AddArgument("--ignore-certificate-errors");
    
            driver = new ChromeDriver(options); // <-- don't forget to pass 'options' here
            driver.Manage().Window.Maximize();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
    
        }
    
        [BeforeScenario]
        public void SetUp()
        {
            container.RegisterInstanceAs<IWebDriver>(driver);
        }
    
        [AfterScenario]
        public void TearDown()
        {
        }
    
        [AfterFeature]
        public static void FeatureTearDown()
        {
            if (driver == null)
                return;
    
            driver.Close();
            driver.Dispose();
            driver = null;
        }
    }
    

    【讨论】:

    • 您也可以使用 FeatureContext 来存储 WebDriver 的实例。您可以将其作为方法的参数获取。
    猜你喜欢
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    相关资源
    最近更新 更多