'How to get Selenium C# control names for reporting

I'm wanting to report a line every time my selenium based automation framework clicks on a control. My object repository is storing individual controls like this:

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

Each time my click method fires I want it to log something like "User clicked on: ExampleControl" However, when I do this I'm getting "User clicked on: sidemenu > ul > li:nth-child(2) > a". Here is my current code:

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

How do I get that Control in the log to show the name of the control rather than the css selector (or whatever other method I'm using to identify the object)?



Solution 1:[1]

I'd recommend a wrapper class to do this:

public class 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;
    }
}

Here's your static call:

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

And the updated function:

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

Solution 2:[2]

Try using nameof(), e.g.:

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

More info here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dbc
Solution 2 misterjake