【问题标题】:Selenium Dynamic Selectors for WebElementsWebElements 的 Selenium 动态选择器
【发布时间】:2017-02-16 20:02:05
【问题描述】:

我正在构建一个测试框架,我的目标是使用该框架测试许多具有相似页面但彼此之间存在轻微差异的网站。

我有一个问题,我希望 WebElements 选择器是动态的,这意味着我想将查找元素的方式作为参数传递给 FindElement 方法。

我正在尝试构建这样的东西:

public class WebComponent
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
            public IWebElement WebElement{get;set;}
            public Accessor Accessor { get; set; }
            public WebComponent()
            {
                Accessor = new Accessor();
            }

    }
    public class Accessor
    {
        OpenQA.Selenium.By By { get; set; }
        public string Value { get; set; }
    }

稍后在我的代码中,当我想拥有此类的实例时:

WebComponent component = new WebComponent();
component.ID = 1;
component.Name = "Logout Button";
component.Description = "The button to click when user wants to logout of website";
component.Accessor.By = By.Id;
component.Accessor.Value = "logout";
component.WebElement = Browser.Driver.FindElement(//missing code);

我的问题是如何使用 component.Accessor 找到 WebElement,任何建议或建议的编辑将不胜感激。

【问题讨论】:

    标签: selenium selenium-webdriver dynamic


    【解决方案1】:

    By.Id 是一个方法组,你不能将它分配给类型OpenQA.Selenium.By。作业应该是

    component.Accessor.By = By.id("logout"); // or any other By and value.
    

    然后你可以使用定位元素

    component.WebElement = Browser.Driver.FindElement(component.Accessor.By);
    

    编辑

    要动态选择定位器和值,您可以执行类似的操作

    private By chooseType(String locatorType, string value) {
        switch(locatorType) {
            case "id":
                return By.id(value);
            case "class":
                return By.className(value);
            //...
        }
    }
    

    【讨论】:

    • 但是这种方式不允许我拥有动态访问方法,它可能会在 {Id、Name、ClassName 等之间发生变化。}
    • @YahyaHHussein 为什么不呢?你可以做component.Accessor.By = By.Id("logout"); 并在component.Accessor.By = By.className("someClass"); 下划线。 Now component.Accessor.ByBy.className("someClass");
    • 想像如果我希望测试人员使用组合框选择访问方法。这种方式将需要每个访问方法的 if 条件。
    • @YahyaHHussein 如果你想要动态定位器,你必须以某种方式选择它们。如果你想避免if else 语句,你可以在返回Byswitch case 方法中进行选择过程,类似于private By chooseType(String locatorType, string value) { switch(locatorType) { case "id": return By.id("logout"); case "class" : return By.className("name");} }
    • 谢谢,这有帮助,请更新您的答案并添加此
    猜你喜欢
    • 2014-10-05
    • 2017-04-13
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 2017-04-21
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多