2012-09-28

Introduction to Selenium WebDriver(Tab test)

In this following article we are going to see a simple code writing in selenium WebDriver using VS 2010.
Please set up environment for selenium webdriver in VS2010 with NUnit(you may see my previous post for that).
What the program will do ?
It will validate the tabs of an website. I am using http://www.kaz.com.bd/ for my example.
First, lets see the site. It has basic 4 tabs Home, Talents,Culture,Contact
image
To validate a tab we need
1. Is there any click event present?
2. Is there is any tab of that name?
3. Is the text (Name of the tab) is same as expected?
4. When we click, does the site goes to the expected destination?(after going there, the title will be loaded)
Step 1 : Launch VS 2010 and Add New Project Name :  KazWebSite, Type : Class Library
Step 2 : Do the library & framework Integration to run web driver( see my previous post) and add a class Named “TestTabKAZ” and add include those libraries in the class(my previous post)
Step 3: Now write assign class as Test Fixture
[TestFixture]

public class TestTabKAZ

Step 4 : Now , define WebDriver[we are using firefox, if you want, just change FirefoxDriver() it to InternetExplorerDriver()], Error logs, base URL



private IWebDriver driver = new FirefoxDriver();

private StringBuilder errors=new StringBuilder();

private string baseURL = "http://www.kaz.com.bd";

Step 5 : Define  TestFixtureTearDown that will run one time after full test execution(Unload related tasks). In here we are quitting the driver and providing a notification to NUnit UI by assert exception if there is any error listed in error logs.


[TestFixtureTearDown]

public void TeardownTest()

{

    try

    {

        driver.Quit();

    }

    catch (Exception)

    {               

    // Ignore errors if unable to close the browser

    }

    Assert.AreEqual("", errors.ToString());

}
Step 6: Define a test case to test Home Tab. In Home tab of the site , we will test
-Title is ok or not(checking by assert string compare)
-Links is present or not(checking by assert true)
-URL link ok or not(checking by assert string compare)
-Home link spelling is ok or not(checking by assert string compare)
and If any error occurs, we will store into Error logs.


[Test]

public void TestHome()

{

    driver.Navigate().GoToUrl(baseURL+"/index.html");

    try

    {

        Assert.AreEqual("http://www.kaz.com.bd/index.html", driver.Url);

        Assert.AreEqual("Home", driver.FindElement(By.LinkText("Home")).Text);//home link

        Assert.AreEqual("Kaz Software", driver.Title);//title ck

        Assert.IsTrue(IsElementPresent(By.LinkText("Home")));//element ck boolean      

    }

    catch (Exception ex)

    {

        errors.Append("\n-Home Error");

        errors.Append(ex.ToString());

        throw ex;

    }

}
Note : In here, to get the element , we use IsElementPresent. It is a private method. For that, add the following code that will use Driver to find element and use NoSuchElementException.



private bool IsElementPresent(By by)

{

    try

    {

        driver.FindElement(by);

        return true;

    }

    catch (NoSuchElementException)

    {

        return false;

    }

}

Step 7 : Like as home tab, add test cases for “Talents”, “Culture”, “Contact” and finally the code will be like this


using System;

using System.Text;

using System.Text.RegularExpressions;

using System.Threading;

using NUnit.Framework;

using OpenQA.Selenium;

using OpenQA.Selenium.Firefox;

using OpenQA.Selenium.Support.UI;

using OpenQA.Selenium.IE;

 

namespace KazWebSite

{

    [TestFixture]

    public class TestTabKAZ

    {

        private IWebDriver driver = new FirefoxDriver();

        private StringBuilder errors = new StringBuilder();

        private string baseURL = "http://www.kaz.com.bd";

        

        [TestFixtureTearDown]

        public void TeardownTest()

        {

            try

            {

                driver.Quit();

            }

            catch (Exception)

            {

                // Ignore errors if unable to close the browser

            }

            Assert.AreEqual("", errors.ToString());

        }

        [Test]

        public void TestHome()

        {

            driver.Navigate().GoToUrl(baseURL + "/index.html");

            try

            {

                Assert.AreEqual("http://www.kaz.com.bd/index.html", driver.Url);

                Assert.AreEqual("Home", driver.FindElement(By.LinkText("Home")).Text);//home link

                Assert.AreEqual("Kaz Software", driver.Title);//title ck

                Assert.IsTrue(IsElementPresent(By.LinkText("Home")));//element ck boolean

            }

            catch (Exception ex)

            {

                errors.Append("\n-Home Error");

                errors.Append(ex.ToString());

                throw ex;

            }

 

        }

        [Test]

        public void TestTalents()

        {

            driver.Navigate().GoToUrl(baseURL + "/talent.html");

            //driver.FindElement(By.LinkText("Talents")).Click();

            try

            {

                Assert.AreEqual("Kaz Software - Talents", driver.Title);

                Assert.AreEqual("Talents", driver.FindElement(By.LinkText("Talents")).Text);

                Assert.IsTrue(IsElementPresent(By.LinkText("Talents")));

                Assert.AreEqual("http://www.kaz.com.bd/talent.html", driver.Url);

            }

            catch (Exception ex)

            {

                errors.Append("\n-Talents Error");

                errors.Append(ex.ToString());

                throw ex;

            }

        }

        [Test]

        public void TestCulture()

        {

            driver.Navigate().GoToUrl(baseURL + "/culture.html");

            //driver.FindElement(By.LinkText("culture")).Click();

            try

            {

                Assert.AreEqual("http://www.kaz.com.bd/culture.html", driver.Url);

                Assert.AreEqual("Kaz Software - Culture", driver.Title);

                Assert.IsTrue(IsElementPresent(By.LinkText("Culture")));

                Assert.AreEqual("Culture", driver.FindElement(By.LinkText("Culture")).Text);

            }

            catch (Exception ex)

            {

                errors.Append("\n-Culture Error");

                errors.Append(ex.ToString());

                throw ex;

            }

        }

        [Test]

        public void TestContact()

        {

            driver.Navigate().GoToUrl(baseURL + "/contact.html");

            //driver.FindElement(By.LinkText("contact")).Click();

            try

            {

                Assert.AreEqual("http://www.kaz.com.bd/contact.html", driver.Url);

                Assert.AreEqual("Kaz Software - Contact", driver.Title);

                Assert.IsTrue(IsElementPresent(By.LinkText("Contact")));

                Assert.AreEqual("Contact", driver.FindElement(By.LinkText("Contact")).Text);

            }

            catch (Exception ex)

            {

                errors.Append("\n-Contact Error");

                errors.Append(ex.ToString());

                throw ex;

            }

        }        

        private bool IsElementPresent(By by)

        {

            try

            {

                driver.FindElement(by);

                return true;

            }

            catch (NoSuchElementException)

            {

                return false;

            }

        }

    }

 

}
Step 8 : Now, build the solution (F6) [Don’t Run by F5 as it is not a executable project and it may show error message]

Step 9 : Open NUnit from Program file , Click Open Project and go to the stored location of the solution of VS project. Open Debug Folder.
image

Select the DLL named TestTabKAZ.dll
image

And Press Open.

Step 10: We will get NUnit GUI loaded with the project that we build. Please see the test cases that should be shown in GUI.
image

Step 11 : Running the Tests. We can run all tests together by selecting the Test Fixture and click Run or we can select an individual test case and Run the test.

If there is any Error, the NUnit GUI will show up with Error like this mentioning the text and which line the error occurs with the expected and actual values.  image

In , we have found the error with RED Bar mentioning error on line 100 as Expected the URL as cultural page where actual was contact page. From the code you can see , this occurs due to contact page load time delay for the Google Map present in contact page. These are real life issues. It may occur though you have written proper test cases. Now, from code , if we check URL at the last so that the page get time to be loaded, this error may not occur. And, its really is

image

We just change the following test part of culture.[testing URL at the end of other tests]


Assert.AreEqual("Kaz Software - Culture", driver.Title);

Assert.IsTrue(IsElementPresent(By.LinkText("Culture")));

Assert.AreEqual("Culture", driver.FindElement(By.LinkText("Culture")).Text);

Assert.AreEqual("http://www.kaz.com.bd/culture.html", driver.Url);

For the page load time, we may use time tracking code to measure load time and define failure cases for performance issues. In here, it will fail for a page if the time is more than 60s.




if (second >= 60) 

   Assert.Fail("timeout");

Now, we run an individual test case . Select TestHome and Run and see the results .

image

Here, the test pass with Green Bar.

So, In this small article, we have seen how to test simple tabs for a webpage. This part’s JAVA will be posted soon.

Thanks for staying with me….:)

Recording in Selenium IDE and Generating WebDriver Code

In this article, we are going to learn how to record steps in selenium IDE. We are going to see some basic path as well as some basic command descriptions.
Step 1 : Please Install IDE & Firefox (for reference you may see one of my previous posts)
Step 2 : Start Firefox
Step 3 : From menu, click tools, and then select Selenium IDE
clip_image002
Step 4 : By default, when IDE opened, it is recording mode( like , it is recording). In the example I am using www.kaz.com.bd this site for practice.
clip_image004
Step 4 : now, From browser go to www.kaz.com.bd
Step 5 : You get a static HTML site with 4 tabs “Home”, “Talents”,” Culture”,” Contact”.
clip_image006
Step 6: click on “Home”, then “Talents”,” Culture”,” Contact” accordingly and from stat menu bar, open selenium IDE UI. You will get those 4 steps listed
clip_image008
Step 7: Press stop button from Selenium IDE (right Upper corner Red Round Button)
Now, you have finished recording where steps are simple clicking tabs.
From the IDE, you can work on those steps like re-run.
Now, We will see how to get web driver Unit test codes (Selenium IDE supported some experimental codes)
Step 1 : To get the code, go to Option –> Options… and check the “Enable experimental features” and press ok
 clip_image010
Step 2: Now, After recording from IDE, click Options -> Format and get the list below
 clip_image012
Step 3: Select c#/NUnit /webDriver ( later on we will also get the JUnit 4 code also) and press OK on warning message( as this is experimental code, so it may be not very accurate).
Now you get the code
clip_image014
In C# Code we have
   1: using System;

   2: using System.Text;

   3: using System.Text.RegularExpressions;

   4: using System.Threading;

   5: using NUnit.Framework;

   6: using OpenQA.Selenium;

   7: using OpenQA.Selenium.Firefox;

   8: using OpenQA.Selenium.Support.UI;

   9:  

  10: namespace SeleniumTests

  11: {

  12:     [TestFixture]

  13:     public class Untitled

  14:     {

  15:         private IWebDriver driver;

  16:         private StringBuilder verificationErrors;

  17:         private string baseURL;

  18:         

  19:         [SetUp]

  20:         public void SetupTest()

  21:         {

  22:             driver = new FirefoxDriver();

  23:             baseURL = "http://www.kaz.com.bd/";

  24:             verificationErrors = new StringBuilder();

  25:         }

  26:         

  27:         [TearDown]

  28:         public void TeardownTest()

  29:         {

  30:             try

  31:             {

  32:                 driver.Quit();

  33:             }

  34:             catch (Exception)

  35:             {

  36:                 // Ignore errors if unable to close the browser

  37:             }

  38:             Assert.AreEqual("", verificationErrors.ToString());

  39:         }

  40:         

  41:         [Test]

  42:         public void TheUntitledTest()

  43:         {

  44:             driver.Navigate().GoToUrl(baseURL + "/");

  45:             driver.FindElement(By.LinkText("Home")).Click();

  46:             driver.FindElement(By.LinkText("Talents")).Click();

  47:             driver.FindElement(By.LinkText("Culture")).Click();

  48:             driver.FindElement(By.LinkText("Contact")).Click();

  49:         }

  50:         private bool IsElementPresent(By by)

  51:         {

  52:             try

  53:             {

  54:                 driver.FindElement(by);

  55:                 return true;

  56:             }

  57:             catch (NoSuchElementException)

  58:             {

  59:                 return false;

  60:             }

  61:         }

  62:     }

  63: }
Step 4 : So, After recording we are getting NUnit code here.
If we make an empty class type project in vs2010(see my previous post on how to create webdriver environment setup) and copy to class to a new empty class, we can run the webDriver Unit test case using NUnit GUI(after building Project)

If we choose the JAVA/JUnit4 webDriver then , we will get the following code
image

In JAVA code we get
   1: package com.example.tests;

   2: 

   3: import com.thoughtworks.selenium.Selenium;

   4: import org.openqa.selenium.*;

   5: import org.openqa.selenium.htmlunit.*;

   6: import org.openqa.selenium.firefox.*;

   7: import org.openqa.selenium.chrome.*;

   8: import org.openqa.selenium.ie.*;

   9: import org.junit.*;

  10: import static org.junit.Assert.*;

  11: 

  12: public class Untitled {

  13:  

  14:     WebDriver driver;

  15:     Selenium selenium;

  16:  

  17:     @Before

  18:     public void startSelenium() {

  19:         driver = new FirefoxDriver();

  20:         selenium = new WebDriverBackedSelenium(driver, "http://www.kaz.com.bd/");

  21:     }

  22:  

  23:     @After

  24:     public void stopSelenium() {

  25:         driver.close();

  26:     }

  27:  

  28:     @Test

  29:     public void testUntitled() {

  30:         selenium.open("/");

  31:         selenium.click("link=Home");

  32:         selenium.waitForPageToLoad("30000");

  33:         selenium.click("link=Talents");

  34:         selenium.waitForPageToLoad("30000");

  35:         selenium.click("link=Culture");

  36:         selenium.waitForPageToLoad("30000");

  37:         selenium.click("link=Contact");

  38:         selenium.waitForPageToLoad("30000");

  39:     }

  40:  

  41: }
If we make a JAVA project in Eclipse(see my previous post on how to create webdriver environment setup) and copy to class to a new empty class, we can run the webDriver Unit test case code Running as JUnit 4.0 test project. 

For detail about Selenium IDE, you can visit the link
Thanks for reading this….:)

This is shantonu's personal blog.Mail[shantonu_oxford@yahoo.com] to contact.

2012-09-26

Setting up Selenium Webdriver

Setting up Selenium Web driver environment in Windows PC

In the following article, we will learn how to setup environment for selenium IDE & selenium Webdriver.

Step 1: Installing Firefox
We need selenium IDE supported Firefox. To know supported Firefox version visit selenium IDE release note . See suitable version number and Download Firefox 
Step 2: Installing Selenium IDE
Run the newly installed Firefox and go to the link 
Download suitable Selenium IDE (Firefox supported, that you have seen from step 1). The Firefox plug-in will be installed.
Or, from Firefox, go to Tools -> add on (Ctrl+Shift+A) search selenium and install selenium IDE. You may find many helping add on. We may need to install when we will start for deeper level coding.

Step3: Selenium Driver Download
Download “Selenium Client Drivers” from here   for JAVA or C# . We will download both as we will setup both environments.Extract the folders and see
For Dot Net: We will get 2 folders for net35& net40 (for different dot Net versions). We have to include DLLs located inside folder as reference of the selenium project in VS 2010.
For JAVA: We will get 2 jar files. selenium-JAVA-2.25.0.jar, selenium-JAVA-2.25.0-srcs.jar. We have to include the jar in the project.

Step 4: IDE and Unit Test Frame Work Installation.
For Dot Net:
1.    Visual studio 2010 should be installed.
2.    NUnit(Download and install latest one)

For JAVA:
1.    Download and install latest Eclipse  or Net Beans(My examples are on Eclipse of that version )
2.    JUnit 4.0 JARs (Already included in eclipse, if not present please install latest one from here )

Step 5 : Including Unit Test framework in the project
For Dot Net : After Crating a Project(class library)
->From solution explorer Right click Reference
-> add reference 
-> Browse
-> Locate to the installed path of NUnit (under program files)
-> bin\framework
->select all (nunit.framework.dll, nunit.mocks.dll, pnunit.framework.dll) and press ok.
For JAVA: After Crating a JAVA Project
-> Mouse right click from Package explorer and click properties
(It also can be found while creating a new JAVA project)
-> build path
 -> Libraries
-> Add Library
-> JUnit
-> JUnit 4.0(not 3.0) and Finish
(Usually it is included in the eclipse, if not, include as external JARs that we have downloaded in step 4

Step 6 : Including Selenium Client Drivers reference  in the project
For Dot Net :
->From solution explorer Right click Reference
-> add reference 
-> Browse
-> Locate to the downloaded & extracted folder path of step 3
-> Select net40
-> include all DLLs (Castle.Core.dll, Ionic.Zip.dll, Newtonsoft.Json.dll, Selenium.WebDriverBackedSelenium.dll, ThoughtWorks.Selenium.Core.dll,
WebDriver.dll, WebDriver.Support.dll)
And press OK.
For JAVA:
-> Mouse right click from Package explorer and click properties
(It also can be found while creating a new JAVA project)
-> build path
 -> Libraries
->Add External JARs
-> Locate to the downloaded & extracted folder path of step 3
->selenium-JAVA-2.25.0.jar 

Step 7 : Add Unit Test framework Header in the Code
In the Class header, we have to add those references that we add in Step 5. Add the header in the top of a Test class.
For Dot Net  :
using NUnit.Framework;
For JAVA :
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

Step 8 : Add Selenium WebDriver Header in the Code
In the Class header, we have to add those references that we add in Step 6. Add the header in the top of a Test class.
For Dot Net  :
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.IE;

For JAVA :
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

Now, we are ready for selenium web driver test implementation.
Be noted that, In Dot Net, we are using class library project type as we will use NUnit GUI for observing test results. And for JAVA, we are using run as JUnit(project) for observing test results.