I’ve been using Selenium for a few years now to write web integration tests, and just realized that I hadn’t really blogged about it. So, here’s a quick rundown of Selenium Web Driver in C# and how it can be used to automate your web page testing.
Selenium is a web testing framework that has undergone years of development and appeared in different iterations. While it is targeted at test applications, under the hood it’s basically just a way to interact with a browser using code. Using this, we can simulate user input and also verify page state to make sure everything happens as we expect it to.
IWebDriver is the starting point of most Selenium tests. This is an interface that represents all the things you can do with a browser – navigate to different pages, interact with elements on the page, switch windows, etc. Because we’re using an interface to do all this interaction, we can swap out the implementation of that interface and not have to change the rest of our test. This means we can switch between Chrome, Firefox, IE, or any other supported browser with minimal changes.
Once we have a driver object, we can tell it to navigate to a certain url and start interacting with the page.
The primary way we’ll be interacting with the page is through it’s elements. Just like with jQuery, you can specify a selector and get back an element (or collection of elements), after which you can perform actions with or query for information. There’s several different ways to find elements using Selenium, including:
- By.Name(“name”) – the name attribute of the element(s)
- By.Id(“id”) – the id attribute of an element
- By.TagName(“p”) – the tag of the element(s)
- By.ClassName(“class”) – the classname of the element(s)
- By.CssSelector(“div > li”) – css selector that matches one or more elements
- and more!
In any case, you can use the FindElement (or FindElements) method of IWebDriver to select those elements. Once you have an element reference, you can execute events or query values:
1 2 3 4
Furthermore, once you have an element, you can search inside of it – those searches will be constrained to the parent element (again, like jQuery).
I’ll probably go into more detail in future posts, but that’s the general idea of Selenium web tests – this is about 90% of what we use of it. I have a working example of this and more advanced scenarios on my github page. You can install Selenium via NuGet.