Friday, July 14, 2017

Learn Selenium (a Test Automation Tool) with C# - Part 2

In this part, we will learn how to a test application to do login Facebook automatically.

For beginning, I want to introduce about XPath. It is a major element in the XSLT standard. XPath can be used to navigate through elements and attributes in an XML document. You can read more about it on here.

In Selenium we will use XPath to find element(s) then make action according to the scenarios for testing.

If you are familiar with FireFox, you can use Firebug and FirePath add-on. They are very popular and strong tools for FireFox web developer. You just need to install them, open a website which you want to test, open Firebug >> click FirePath tab >> click the pointer and select an element on the page for getting its XPath value. See the following picture for example:

If your are familiar with Chrome, you can use XPath-Helper extension. But I recommend you use a built-in function of Chrome DevTools. Just open the website, press F12 then press Ctrl + F to enable DOM searching box. Using pointer to point an element then key a XPath value in to searching box for finding matched elements. If the matching is only 1, it is the XPath for this element.

For searching, you can try the first search with syntax:  .//*[@attribute-name='value']
For example a element having id="email", you can try: .//*[@id='email']

Another way on Chrome is using Console panel of Chrome DevTools with the function $x("XPath value"). For example: $x(".//*[@id='email']")

OK, that's enough for XPath. It's time to code our test application. Yes, let see the code first and I will explain later:

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumTutorial
    class Program
        static void Main(string[] args)
            IWebDriver wd = new ChromeDriver(@"E:\working\abc\SeleniumTutorial");
            wd.Url = "";
            wd.FindElement(By.XPath(@"//input[@value='Đăng nhập']")).Click();


Comparing with Part 1, the blue codes are new. In which:
wd.Manage().Window.Maximize(); ==> to maximize the browser window

Next 2 lines are for finding email box, password box and input (SendKeys) its values. The last line is for finding login button (it depends on the language used on the browser, mine is Vietnamese ). See below picture for more understanding:

Why I don't use @id to find login button? Because I recognize that Facebook changes this id frequently. So I use its value instead of.

Walking through Part 1 & Part 2, I believe that you have enough basic knowledge to start your automation test application with Selenium. Let's practice.

Happy coding! Any comment is welcome.

Subscribe to RSS Feed Follow me on Twitter!