Sunday 14 June 2015

Page Object Model For Selenium WebDriver

 Click Here to  Download Complete Project


Page Object Model Framework in Selenium:

              Page Object Model Framework has now a days become very popular test automation framework in the industry and many companies are now adopting it because of its easy test maintenance and reduces the duplication of code. 
  • The main advantage of Page Object Model is that if the UI element / Controls changes for any page, it doesn't require us to change any Tests . 
  • We just need to change only the code within the page objects. This framework is mostly used with Selenium. 
  • It is one Design Pattern for Selenium Code.
  • It Provides the clean separation page code from Test code.

             In Page Object Model we are going to Create a Separate class for separate Web Page. In that class we are going to map UI elements as a object and their respective action on these controls such as "signIn" or "sign-Up" or "Forget password".

Each action on a page (controls) can be represented as a method in their respective class. so Finally we can say that - "Each page has respective class containing UI element(Locators of each element on that page ) and their respective actions as a "Method" in that class.  

See in a below screen shot-
        Here I am considering facebook applicatios "HomePage". I have Used POM framework to Test Facebook Application. I have written Three Test. we will see in later part......
 


UI Element and their Locators:

        static IWebDriver driver = null;
        static IWebElement element = null;
        //(UIObject) Locators for Login/SignIn
        static By userName = By .Id("email");
        static By Password = By .Id("pass");
        static By LogIn = By .XPath("//input[@type='submit'][@value='Log In']");
              
        // (UIObject) Locators for to Register a New User on Facebook Application
        static By FirstName = By .Id("u_0_1");
        static By LastName = By .Id("u_0_3");
        static By Email = By .Id("u_0_5");
        static By ReEmail = By .Id("u_0_8");
        static By NewPassword = By .Id("u_0_a");
        static By Month = By .Id("month");
        static By Day = By .Id("day");
        static By Year = By .Id("year");
        static By GenderFemale = By .Id("u_0_d");
        static By GenderMale = By .Id("u_0_e");
        static By SignUp = By .Id("u_0_i");

Respective Action on UI element:
         /// <summary>
        /// Set the user Name to be Logged in.
        /// </summary>
        /// <param name="UserName">
UserName to be Log-In</param>
        public static void setUserName(String UserName)
        {
            driver.FindElement(userName).SendKeys(UserName);
        }

        /// <summary>
        /// Set the Password, in the password field of facebook application.
        /// </summary>
        /// <param name="UserPassword">
Password of user wants to Log-in.</param>
        public static void setUserPassword(String UserPassword)
        {
            driver.FindElement(Password).SendKeys(UserPassword);
        }

        /// <summary>
        /// Clcik on Login In Button.
        /// </summary>
        public static void ClickLogin()
        {
            driver.FindElement(LogIn).Click();
        }

Advantages of Framework:

  • The biggest advantage of the software framework is that it reduces the time and energy in developing any software.
  • There is clean separation between test code and page specific code such as locators.
  • Code Maintainability
  • More Readability.
  • Less Error Prone.
  • Seperation of Concern.
  • Framework follow design pattern, so when you use these frameworks you’ve to follow their coding convention which makes your code clean and extensible for future purpose.
  • Framework separates business logic from user interface making the code cleaner and extensible.
  • Frameworks help you to develop the project rapidly, if you know one framework well then you’ll never worry about the project deadline.

How to setup Page Object Model In Visual Studio ( Selenium with C# & NUnit )

Pre-requisite:

  • Visual studio Any version (I have used 2012).
  • NUnit 2.6.4
  • Selenium webdriver (selenium-server-standalone-2.46.0.jar)

Steps to Create:

Open Visual Studio
1- Select New Project -> select Visual C# -> select Class Library. give Name as PageObjectModel.
     Add the  references for Selenium

2- Select the Solution and right click add->New Project->Test->Unit Test.
Add the references for NUnit Testing Framework.

Description:
  • The Class Library project contains the selenium code ( Webpage UI Element and their respective actions )
.
The Next, Test project contains the Test  code only.

  • The  standard says Your class Library should be depends on selenium and your Test should be independent.


Project Structure:
    See the below screen shot for Project structure in a project. 



=============================================================================================
Class library project Contains Following files:

Browser.cs : Common file used to set the Browser while executing the Test.

HomePage.cs: Contains the "Login" and "sign-Up" Actions

AfterLogin.cs: Contains the "UpdateStatusOnfacebook" & "Loggedout" actions.

RegisterPage.cs: Contains the "getTitle" action.

Test Project contains following files:

AfterLoginTest.cs: Test the functionality of Successful "Login" and after "UpdateStatusOnfacebook".

HomePage.cs:Test the functionality of "Login" successful and "RegisterNewUser".

Project Code:

File Browser.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.IE;


namespace PageObjectModel
{
    public class Browser
    {
        static IWebDriver driver = null ;

        public static String BrowserName = null ;


        /// <summary>
        /// set the Browser in which Application should be opened.
        /// </summary>
        /// <param name="BName">Enter the Name of Browser</param>
        /// <returns>Newly created instance of Respective Browser</returns>

        public static IWebDriver SetBrowserName(String BName)
        {
            switch (BName)
            {
                case "firefox":
                    {
                        driver = new FirefoxDriver();
                        break;
                    }
                case "chrome":
                    {

                        driver = new ChromeDriver("G:\\Selenium\\LatestDriver\\chromedriver_win32");
                        break;
                    }
                case "ie":
                    {
                        driver = new InternetExplorerDriver("G:\\Selenium\\LatestDriver\\IEDriverServer_Win32_2.46.0");
                        break;
                    }
                default:
                    {
                        driver = null;
                        break;
                    }
            }
            return driver;
        }

        /// <summary>
        /// Close the current Browser/Application
        /// </summary>

        public static void Close()
        {
            driver.Close();
        }
    }
}


File HomePage.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.IE;


namespace PageObjectModel
{
    public class HomePage
    {

        static IWebDriver driver = null;
        static IWebElement element = null;
        //(UIObject) Locators for Login/SignIn
        static By userName = By .Id("email");
        static By Password = By .Id("pass");
        static By LogIn = By .XPath("//input[@type='submit'][@value='Log In']");


        // (UIObject) Locators for to Register a New User on Facebook Application
        static By FirstName = By .Id("u_0_1");
        static By LastName = By .Id("u_0_3");
        static By Email = By .Id("u_0_5");
        static By ReEmail = By .Id("u_0_8");
        static By NewPassword = By .Id("u_0_a");
        static By Month = By .Id("month");
        static By Day = By .Id("day");
        static By Year = By .Id("year");
        static By GenderFemale = By .Id("u_0_d");
        static By GenderMale = By .Id("u_0_e");
        static By SignUp = By .Id("u_0_i");


        /// <summary>
        /// Constructor to initialize set the browser for Homepage
        /// </summary>
        /// <param name="driverr">Tell us on which Browser the application is going to open</param>

        public HomePage(IWebDriver driverr)
        {
            driver = driverr;
        }

        /// <summary>
        /// Set the Browser on which the application is to be Run/Test.
        /// </summary>
        /// <param name="BrowserName">Name of browser to be Set</param>
        /// <returns>Instance of newely set Browser</returns>

        public static IWebDriver setbrowser(String BrowserName)
        {
            driver = Browser.SetBrowserName(BrowserName);
            return driver;
        }

        /// <summary>
        /// Set the URL of an Application to be Test
        /// </summary>
        /// <param name="url">URL of Your Application under Test.</param>

        public static void SetURL(String url)
        {
            driver.Manage().Window.Maximize();
            driver.Navigate().GoToUrl(url);
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
        }

        /// <summary>
        /// Set the user Name to be Logged in.
        /// </summary>
        /// <param name="UserName">UserName to be Log-In</param>

        public static void setUserName(String UserName)
        {
            driver.FindElement(userName).SendKeys(UserName);
        }

        /// <summary>
        /// Set the Password, in the password field of facebook application.
        /// </summary>
        /// <param name="UserPassword">Password of user wants to Log-in.</param>

        public static void setUserPassword(String UserPassword)
        {
            driver.FindElement(Password).SendKeys(UserPassword);
        }

        /// <summary>
        /// Clcik on Login In Button.
        /// </summary>

        public static void ClickLogin()
        {
            driver.FindElement(LogIn).Click();
        }

        /// <summary>
        /// Click on Logged in Button after filling UserName and Password field.
        /// </summary>
        /// <param name="userName">User Name of User</param>
        /// <param name="Password">Password of User.</param>
        /// <returns>Return/Directed to the Next page after successful of Registering the User.</returns>

        public static AfterLogin ClickOnLogin(String userName, String Password)
        {
            setUserName(userName);
            setUserPassword(Password);
            ClickLogin();
            return new AfterLogin(driver);
        }

        /// <summary>
        /// Get the Title/Constant String from Home Page to Identify each page from each other.
        /// </summary>
        /// <returns></returns>

        public static String getTitle()
        {
            return driver.Title;
        }

        //II Test Part 
        // second part of Action in a HomePage is  Register a User

        /// <summary>
        /// Set the New User name to be Register.
        /// </summary>
        /// <param name="firstName">Enter First name of User</param>

        public static void SetRegisterUserFirstName(String firstName)
        {
            driver.FindElement(FirstName).SendKeys(firstName);
        }

        /// <summary>
        /// Set the New User Last Name to be Register.
        /// </summary>
        /// <param name="lastName">last Name of New User</param>

        public static void SetRegisterUserLastName(String lastName)
        {
            driver.FindElement(LastName).SendKeys(lastName);
        }

        /// <summary>
        /// Set the Email of New user for Verification.
        /// </summary>
        /// <param name="eMail">Enter Email of New user for verification</param>

        public static void SetEmail(String eMail)
        {
            driver.FindElement(Email).SendKeys(eMail);
        }

        /// <summary>
        /// Re-Enter the mail
        /// </summary>
        /// <param name="reEmail">Re-Enter the mail of new user </param>

        public static void SetReEMail(String reEmail)
        {
            driver.FindElement(ReEmail).SendKeys(reEmail);
        }

        /// <summary>
        /// Set the Password for Facebook login for new user
        /// </summary>
        /// <param name="newPassword">Enter New password</param>

        public static void SetNewPassword(String newPassword)
        {
            driver.FindElement(NewPassword).SendKeys(newPassword);
        }

        /// <summary>
        /// Select the Month from Drop Down List.
        /// </summary>
        /// <param name="month">Enter your Birth Month  </param>

        public static void SelectMonth(String month)
        {

            SelectElement select = new SelectElement(driver.FindElement(Month));
            foreach (IWebElement item in select.Options)
            {
                if (item.Text.Contains(month))
                    item.Click();
            }
        }

        /// <summary>
        /// select  the year of Your Birth from Drop DownList.
        /// </summary>
        /// <param name="year">Enter Your year of Birth.</param>

        public static void SelectYear(String year)
        {
            SelectElement select = new SelectElement(driver.FindElement(Year));
            foreach (IWebElement item in select.Options)
            {
                if (item.Text.Contains(year))
                    item.Click();
            }
        }

        /// <summary>
        /// Select Birth day from drop DownList.
        /// </summary>
        /// <param name="day">Enter your Birthday.</param>

        public static void SelectDay(String day)
        {
            SelectElement select = new SelectElement(driver.FindElement(Day));
            foreach (IWebElement item in select.Options)
            {
                if (item.Text == day)
                    item.Click();
            }
        }

        /// <summary>
        /// select Your Gender
        /// </summary>
        /// <param name="gender">select Male / Female</param>

        public static void selectGender(String gender)
        {
            String genderr = gender.ToLower();
            element = driver.FindElement(GenderMale);
            if (element.Text.ToLower() == genderr)
            {
                element.Click();
            }
            else
            {
                element = driver.FindElement(GenderFemale);
                element.Click();
            }
            element = null;
        }

        /// <summary>
        /// Click on signUp Button
        /// </summary>

        public static void ClickSignUp()
        {
            driver.FindElement(SignUp).Click();
        }

        /// <summary>
        /// Register  the new User with His/Her details.
        /// </summary>
        /// <param name="firstName">Name of User.</param>
        /// <param name="lastname">Last Name Of User.</param>
        /// <param name="eMail">Existing Email of User.</param>
        /// <param name="reEmail">Re-Enter the Existing E-mail.</param>
        /// <param name="newPassword">Enter New Password to access facebook Application</param>
        /// <param name="month">month of Birth.</param>
        /// <param name="day">Birth Day</param>
        /// <param name="year">Birth Year</param>
        /// <param name="gender">male/Female</param>
        /// <returns>Return or Redirect to register Page.</returns>

        public static Registerpage RegisterNewUser(string firstName, String lastname, String eMail, String reEmail, string newPassword, String month, string day, string year, String gender)
        {
            SetRegisterUserFirstName(firstName);
            SetRegisterUserLastName(lastname);
            SetEmail(eMail);
            SetReEMail(reEmail);
            SetNewPassword(newPassword);
            SelectMonth(month);
            SelectDay(day);
            SelectYear(year);
            selectGender(gender);
            ClickSignUp();
            System.Threading.Thread.Sleep(5000);
            return new Registerpage(driver);
        }


    }
}


Click Here to  Download Complete Project

 

See Also:

32 comments:

  1. hi welcome to this blog. really you have post an informative blog. it will be really helpful to many peoples. thank you for sharing this blog.
    selenium training in chennai

    ReplyDelete
    Replies
    1. Thank you for sharing such a great article. IntelliMindz is the best IT Training in Bangalore with placement, offering 200 and more software courses with 100% Placement Assistance.


      Selenium Online Course
      Selenium Training In Bangalore
      Selenium Training In Chennai
      Selenium Training In Coimbatore
      Selenium Training In Tirupur


      Delete
  2. Thanks Avinash for sharing a great article, It was very helpful..
    Best Selenium training institute in Chennai

    ReplyDelete
  3. A Crystal Clear guide to know about page object model for selenium webdriver, Here check the latest update in Selenium WebDriver - Selenium Training in Chennai

    ReplyDelete
  4. Hi..Nice Article. How do we handle fluent waits, explicit waits on expected conditions when using page factory...when some elements appear dynamically.Best Software Testing in Chennai

    ReplyDelete
  5. SELENIUM
    From My search…Creating Experts provides Best Selenium Training with real time projects assistance.Most of the modules are equipped with advance level topics which the student can learn from the basics to the advance level stage.They also provide placement assistance in leading MNC companies across the globe according to the current requirements.
    And these are the Best selenium training institute which provides Real Time Hands on Training…
    http://thecreatingexperts.com/selenium-training-in-chennai/
    Codedion Technologies-9003085882
    Creating Experts-8122241286
    They also providing both Classroom/Online Training

    ReplyDelete
  6. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    rpa Training in Chennai

    rpa Training in bangalore

    rpa Training in pune

    blueprism Training in Chennai

    blueprism Training in bangalore

    blueprism Training in pune

    rpa online training

    ReplyDelete
  7. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.

    automation anywhere training in chennai

    automation anywhere training in bangalore

    automation anywhere training in pune

    automation anywhere online training

    blueprism online training

    rpa Training in sholinganallur

    rpa Training in annanagar

    ReplyDelete
  8. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    Devops Training in Chennai

    Devops Training in Bangalore

    Devops Training in pune

    Devops training in tambaram

    ReplyDelete
  9. I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
    python training institute in chennai
    python training in Bangalore
    python training in pune
    python online training

    ReplyDelete
  10. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
    java training in tambaram | java training in velachery

    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

    ReplyDelete
  11. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
    python training in rajajinagar
    Python training in btm
    Python training in usa
    Python training in marathahalli

    ReplyDelete
  12. Thank you so much for a well written, easy to understand article on this. It can get really confusing when trying to explain it – but you did a great job. Thank you!
    Blueprism training in Chennai

    Blueprism training in Bangalore

    Blueprism training in Pune

    ReplyDelete
  13. Wonderful article, very useful and well explanation. Your post is extremely incredible. I will refer this to my candidates...
    Blueprism training in tambaram

    Blueprism training in annanagar

    Blueprism training in velachery

    ReplyDelete
  14. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    Data science training in tambaram | Data Science training in anna nagar
    Data Science training in chennai | Data science training in Bangalore
    Data Science training in marathahalli | Data Science training in btm

    ReplyDelete
  15. Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.

    angularjs-Training in chennai

    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    ReplyDelete
  16. Really nice experience you have. Thank you for sharing. It will surely be an experience to someone.
    java training in jayanagar | java training in electronic city

    java training in chennai | java training in USA

    ReplyDelete

  17. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.

    AWS Interview Questions And Answers

    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

    AWS Training in Pune | Best Amazon Web Services Training in Pune

    Amazon Web Services Training in Pune | Best AWS Training in Pune

    AWS Online Training | Online AWS Certification Course - Gangboard

    ReplyDelete
  18. Appreciating the persistence you put into your blog and detailed information you provide.Thanks for your blog
    Azure training chennai | Azure training course chennai

    ReplyDelete
  19. I really enjoy the blog.Much thanks again. Really Great. selenium online training

    ReplyDelete
  20. Good to know about the email list business. I was looking for such a service for a long time o grow my local business but the rates that other companies were offering were not satisfactory. Thanks for sharing the recommendations in this post!Automation Anywhere Training in Bangalore

    ReplyDelete
  21. An interesting discussion is worth comment. I think that you should publish more on this subject matter, it may not be a taboo matter but usually people don't speak about site such subjects. To the next! Many thanks!!

    ReplyDelete
  22. At a high level, you can control all of these with extensive administrative controls accessible via a secure Web client.For more information visit
    AWS training in chennai | AWS training in anna nagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery

    ReplyDelete
  23. Good post and informative. Thank you very much for sharing this good article, it was so good to read and useful to improve my knowledge as updated, keep blogging.
    oracle training in chennai

    oracle training institute in chennai

    oracle training in bangalore

    oracle training in hyderabad

    oracle training

    oracle online training

    hadoop training in chennai

    hadoop training in bangalore

    ReplyDelete
  24. Are you looking for Big Data training in Chennai with placement opportunities? Then we, Infycle Technologies are with you to make your dream into reality. Infycle Technologies is one of the best Big Data Training Institute in Chennai, which offers various programs along with Big Data such as Oracle, Java, AWS, Hadoop, etc., in complete hands-on practical training with trainers, those are specialists in the field. In addition to the training, the mock interviews will be arranged for the candidates, so that they can face the interviews with the best knowledge. Of all that, 100% placement assurance will be given here. To have the words above in the real world, call 7502633633 to Infycle Technologies and grab a free demo to know more. Big Data Training in Chennai

    ReplyDelete
  25. Study Hadoop for making your career as a shining sun with Infycle Technologies. Infycle Technologies offers the best Hadoop Training in Chennai, providing complete hands-on practical training of professional specialists in the field. In addition to that, it also offers numerous programming language tutors in the software industry such as Oracle, Python, Big Dat, Hadoop, etc. Once after the training, interviews will be arranged for the candidates, so that, they can set their career without any struggle. Of all that, 100% placement assurance will be given here. To have the top career in IT industry, dial 7502633633 to Infycle Technologies and grab a free demo to know more.

    http://infycletechnologies.com/big-data-training-in-chennai/

    ReplyDelete
  26. If salary is your only income means. Simply think to make it HIGH by getting into AWS training institute in Chennai, Infycle. It will be so easier for you because, past 15 years software industry Infycle leads a 1 place for giving a best students in IT industry.

    ReplyDelete