【问题标题】:How to use generics and factory design to instantiate PageObject classes如何使用泛型和工厂设计来实例化 PageObject 类
【发布时间】:2019-06-23 13:31:41
【问题描述】:

我正在用 c# 开发一个 selenium 框架。页面类使用工厂设计实例化以隐藏实例化逻辑,我希望能够使用 var myPageClass = HelperSelenium.Instance(MyPageClass) 而不是 var myPageClass = MyPageClass.Instance(driver)

我尝试在 HelperSelenium 类中创建一个泛型函数,但我还不能完全理解泛型的工作原理。

PageObject 类示例(注意我使用 Instance 方法来实例化该类

public class HomePage : BasePage
{       
    private HomePage(IWebDriver driver, CountryEnum enum) : base(driver) { }

    private static HomePage homePage { get; set; }

    public static HomePage Instance(IWebDriver driver, CountryEnum enum)
    {
        switch (enum)
        {
             case CountryEnum.Sweden:
                 HomePage = new HomePage_SWE(driver);
                 break;
             case CountryEnum.Germany:
                 HomePage = new HomePage_GER(driver);
                 break;
             case CountryEnum.Italy:
                 HomePage = new HomePage_ITA(driver);
                 break;
             default:
                 HomePage = new HomePage_UK(driver);
                 break;
        }

        return homePage;
    }

...
}
public T InstancePage<T>() where T : BasePage
{
    return (T).Instance(WebDriver, CountryEnum.Sweden);
}
Error   CS0119  'T' is a type, which is not valid in the given context  InfrastructureSelenium  C:\testSelenium\Infrastructure\Helper\HelperSelenium.cs 140 Active
Error   CS0119  'T' is a type parameter, which is not valid in the given context    InfrastructureSelenium  C:\testSelenium\Infrastructure\Helper\HelperSelenium.cs 140 Active

【问题讨论】:

  • T 是一种类型。您会看到,当您使用 new 关键字时,您会创建一个类的特定实例。 T 只是一种类型。这不是一个例子。把它想象成房子的蓝图。 T 只是一个蓝图。通过使用new MyClass,您构建了建筑物(一个实例)。您仍然可以使用架构,但不能在架构上调用 OpenDoor() 方法。你必须先盖房子。
  • 谢谢你,费尼奥。我的想法是,如果我将接口 IPage 作为类型传递,则接口实现实例方法,每个类都必须实现该方法。这样,在我的脑海中,我应该能够做到。但是我不确定这种方式是否可行。
  • 你想只对主页使用泛型吗?
  • 不,它会针对框架中的每个页面,大约 200 个类
  • 你不能让HomePage 和其他类通用,而不是将每个类与国家代码相乘吗?

标签: c# selenium generics factory pageobjects


【解决方案1】:

最后我通过使用:

        public T InstantiatePage<T>() where T : class
    {
        // COUNTRY code as defined in
        // https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements
        var className = string.Format("{0}_{1}", typeof(T).FullName, getCulture()); 

        // T will be base class if no derived class with COUNTRY code suffix is found 
        var classType = Type.GetType(className) ?? typeof(T);

        // Instantiate the page
        var instance = Activator.CreateInstance(classType, new object[] { WebDriver });

        return (T)instance;
    }

我很确定使用 PageObject.PageFactory 会更好

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多