How do I use Selenium in C#?

后端 未结 9 951
孤街浪徒
孤街浪徒 2020-12-01 06:38

Selenium.

I downloaded the C# client drivers and the IDE. I managed to record some tests and successfully ran them from the IDE. But now I want to do that using C#. I

9条回答
  •  误落风尘
    2020-12-01 07:30

    One of the things that I had a hard time finding was how to use PageFactory in C#. Especially for multiple IWebElements. If you wish to use PageFactory, here are a few examples. Source: PageFactory.cs

    To declare an HTML WebElement, use this inside the class file.

    private const string _ID ="CommonIdinHTML";
    [FindsBy(How = How.Id, Using = _ID)]
    private IList _MultipleResultsByID;
    
    private const string _ID2 ="IdOfElement";
    [FindsBy(How = How.Id, Using = _ID2)]
    private IWebElement _ResultById;
    

    Don't forget to instantiate the page object elements inside the constructor.

    public MyClass(){
        PageFactory.InitElements(driver, this);
    }
    

    Now you can access that element in any of your files or methods. Also, we can take relative paths from those elements if we ever wish to. I prefer pagefactory because:

    • I don't ever need to call the driver directly using driver.FindElement(By.Id("id"))
    • The objects are lazy initialized

    I use this to write my own wait-for-elements methods, WebElements wrappers to access only what I need to expose to the test scripts, and helps keeps things clean.

    This makes life a lot easier if you have dynamic (autogerated) webelements like lists of data. You simply create a wrapper that will take the IWebElements and add methods to find the element you are looking for.

提交回复
热议问题