首页 > 解决方案 > 如何获取 Selenium C# 控件名称以进行报告

问题描述

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

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

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

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

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

标签: c#seleniumselenium-webdriverui-automationqa

解决方案


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

公共类 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);
}

推荐阅读