【问题标题】:How to get Selenium C# control names for reporting如何获取 Selenium C# 控件名称以进行报告
【发布时间】:2018-09-06 14:52:32
【问题描述】:

每当我的基于 selenium 的自动化框架单击控件时,我都想报告一行。我的对象存储库正在存储这样的单个控件:

public static By ExampleControl = By.CssSelector("sidemenu > ul > li:nth-child(2) > a");

每次我的 click 方法触发时,我希望它记录类似“用户点击:ExampleControl”之类的内容但是,当我这样做时,我得到“用户点击:sidemenu > ul > li:nth-child(2) > 一个”。这是我当前的代码:

        public void Click(OpenQA.Selenium.By Control)
    {
        WaitForControlClickable(Control);
        TestInitiator.driver.FindElement(Control).Click();
        reporter.LogInfo("User clicked on: " + Control);
    }

如何在日志中获取该控件以显示控件的名称而不是 css 选择器(或我用来识别对象的任何其他方法)。

【问题讨论】:

    标签: c# selenium selenium-webdriver ui-automation qa


    【解决方案1】:

    我推荐一个包装类来做到这一点:

    公共类 ByControlWithName {

        public OpenQA.Selenium.By Control { get; set; }
        public string ControlName { get; set; }
    
        public ByControlWithName(OpenQA.Selenium.By ctl, string name)
        {
            this.Control = ctl;
            this.ControlName = name;
        }
    
    
    }
    

    这是你的静态调用:

    public static ByControlWithName ExampleControl = new ByControlWithName(By.CssSelector("sidemenu > ul > li:nth-child(2) > a"), "ExampleControl");
    

    以及更新后的功能:

    public void Click(ByControlWithName Control)
    {
        WaitForControlClickable(Control.Control);
        TestInitiator.driver.FindElement(Control.Control).Click();
        reporter.LogInfo("User clicked on: " + Control.ControlName);
    }
    

    【讨论】:

    • 我尝试过这种方法,但我的脚本现在抛出异常:OpenQA.Selenium.StaleElementReferenceException: stale element reference: element is not attach to the page document
    • @Staindz - 我必须更改它,以便在点击之前抓取元素的信息......点击为时已晚,因为它已经刷新了页面
    • 所以我花了一分钟的时间来了解您的代码在做什么,但现在我明白为什么它不适合我了。我通过 xpath 和 CSS 选择器访问大多数对象。我有一个对象存储库,它们具有“名称”,但是当我引用该对象时,它会为我提供 selenium 用来在页面上查找对象的任何内容(xpath、名称、id 或 css 选择器)。我已经为这个对象分配了一个名称,我只需要将它打印在我的日志中。在我的原始帖子中,您可以看到我如何存储对象的示例,“ExampleControl”是我想要传递到日志的名称。
    • 我认为你需要一个第二个参数并在每次调用它时将 nameof 示例传递给它
    • 这也是我能想到的唯一解决方案,不幸的是,这不是一种干净的方法,因为在我的所有测试中都会不断调用它。不过,我很感谢你和我一起看这个。
    【解决方案2】:

    尝试使用nameof(),例如:

    reporter.LogInfo("User clicked on: " + nameof(Control));

    更多信息here

    【讨论】:

    • 感谢您的快速响应,我尝试实现这一点并最终得到:“用户点击:控件”而不是控件的实际名称。
    猜你喜欢
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多