Working with Page Factory and Webdriver

We have been seeing examples of webdriver being implemented across the testing world, but is just knowing how to use the APIs all about knowing Webdriver? the answer is NO! Let us go one step further, let us know about Page Factory..where every time you access a WebElement it will perform a search to find the element on the page.

You can find the API for page factory here:
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/PageFactory.html

This has some advantages:

  • When the PageFactory is initialised the proxies are configured, but the WebElements are not found at that point (so you won't get a NoSuchElementException)
  • Every time you use a WebElement it will go and find it again so you shouldn't see StaleElementException's


But when you use the @CacheLookup annotation, which is losing you the second benefit as it will find the element once and then keep a reference to it, you are now far more likely to see StaleElementExceptions.
One more thing you need to know handy is usage of @FindBy annotation, Do not get confused on all this terms, we will hit them one by one.


1.@FindBy

This is used to mark a field on a Page Object to indicate an alternative mechanism for locating the element or a list of elements. Used in conjunction withPageFactory this allows users to quickly and easily create PageObjects.You can either use this annotation by specifying both "how" and "using" or by specifying one of the location strategies (eg: "id") with an appropriate value to use. Both options will delegate down to the matching By methods in By class.

For example, these two annotations point to the same element: @FindBy(id = "foobar") WebElement foobar; @FindBy(how = How.ID, using = "foobar") WebElement foobar; and these two annotations point to the same list of elements: @FindBy(tagName = "a") List links; @FindBy(how = How.TAG_NAME, using = "a") List links; So, We are taking about making the test looks simple and easy to maintain using @FindBy, we will see more example soon!



2. PageFactory.initElements

Instantiate an instance of the given class, and set a lazy proxy for each of the WebElement and List fields that have been declared, assuming that the field name is also the HTML element's "id" or "name". This means that for the class: public class Page { private WebElement submit; } there will be an element that can be located using the xpath expression "//*[@id='submit']" or "//*[@name='submit']" By default, the element or the list is looked up each and every time a method is called upon it. To change this behaviour, simply annotate the field with the CacheLookup. To change how the element is located, use the FindBy annotation. This method will attempt to instantiate the class given to it, preferably using a constructor which takes a WebDriver instance as its only argument or falling back on a no-arg constructor. An exception will be thrown if the class cannot be instantiated.

 public class SignInTest extends TestCase
 {
 @Test
 public void SignInWithValidCredentialsTest() {
 SignInPage signInPage = PageFactory.initElements(driver, SignInPage.class);
 MainPage mainPage = signInPage.signInWithValidCredentials("sbrown", "sbrown"); assertThat(mainPage.getTitle(), is(equalTo(driver.getTitle())));
}
}
Let us now try the example page used in http://www.whiteboxtest.com/selenium-test1.php
You can see some links, button etc which can be used for test purpose. For this page we have the following: @FindBy(how = How.ID, using = "id-012") WebElement verifybutton;
 public void clickButtonPresentByID_id012() {
 verifybutton.click();
} // Find and click selenium-test2 public SeleniumTest2 clickSeleniumTest2() { // Find the text link by its name WebElement someElement = driver.findElement(By.linkText("selenium-test2"));
// Click the link text someElement.click();
return PageFactory.initElements(driver, SeleniumTest2.class);
}

For http://www.whiteboxtest.com/selenium-test2.php page following changes done in page object class
@FindBy(how = How.ID, using = "q2") WebElement textBox;
// Find the text box by ID public void inputTextBox(String txt) { textBox.clear(); textBox.sendKeys(txt);
}
// Find and click selenium-test1 public SeleniumTest1 clickSeleniumTest1() { // Find the text link by its name WebElement someElement = driver.findElement(By.linkText("selenium-test1"));
// Click the link text someElement.click();
return PageFactory.initElements(driver, SeleniumTest1.class);
}

Test cases code following changes done
SeleniumTest1 seleniumTest1 = PageFactory.initElements(driver, SeleniumTest1.class); seleniumTest1.clickButtonPresentByID_id012(); SeleniumTest2 seleniumTest2 = seleniumTest1.clickSeleniumTest2(); seleniumTest2.inputTextBox("hello"); seleniumTest1 = seleniumTest2.clickSeleniumTest1();

Let us look at the complete code here:
testMain.java:

 package test.selenium.pagefactory;
 import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;

public class testMain { public static void main(String[] args)
{ // Create a new instance of the Firefox driver
 WebDriver driver = new FirefoxDriver(); // Now use the firefox instance driver to open a page URL driver.get("http://www.whiteboxtest.com/selenium-test1.php"); // driver.navigate().to("http://www.google.com"); alternative to open a // URL SeleniumTest1 seleniumTest1 = PageFactory.initElements(driver, SeleniumTest1.class); seleniumTest1.clickButtonPresentByID_id012(); SeleniumTest2 seleniumTest2 = seleniumTest1.clickSeleniumTest2(); seleniumTest2.inputTextBox("hello"); seleniumTest1 = seleniumTest2.clickSeleniumTest1(); // Close and clean firefox driver instance driver.quit();
}}

SeleniumTest1.java

package test.selenium.pagefactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.*;

public class SeleniumTest1 {
WebDriver driver;
@FindBy(how = How.ID, using = "id-012")
WebElement verifybutton;

public SeleniumTest1(WebDriver driver) {
this.driver = driver;
// you may Check title of the page and assert if page title is incorrect
System.out.println("Page title is: " + driver.getTitle());
}

public void clickButtonPresentByID_id012() {
verifybutton.click();
}
// Find and click selenium-test2
public SeleniumTest2 clickSeleniumTest2() {
// Find the text link by its name
WebElement someElement = driver.findElement(By.linkText("selenium-test2"));
// Click the link text
someElement.click();
return PageFactory.initElements(driver, SeleniumTest2.class);
}
// Find and click selenium-test3
}

SeleniumTest2.java

 package test.selenium.pagefactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.*;
public class SeleniumTest2 { WebDriver driver; @FindBy(how = How.ID, using = "q2") WebElement textBox;
 public SeleniumTest2(WebDriver driver) { this.driver = driver; // you may Check title of the page and assert if page title is incorrect System.out.println("Page title is: " + driver.getTitle());
}
 // Find the text box by ID
 public void inputTextBox(String txt) {
 textBox.clear();
 textBox.sendKeys(txt);
}
 // Find and click selenium-test1
 public SeleniumTest1 clickSeleniumTest1()
{ // Find the text link by its name 
WebElement someElement = driver.findElement(By.linkText("selenium-test1"));
 // Click the link text someElement.click(); return new SeleniumTest1(driver);
}
 // Find and click selenium-test3
}

Comments

  1. where is SignInPage.class? Error shown as SignInPage cannot be resolved to a type

    ReplyDelete
  2. page factory for python selenium

    ReplyDelete
  3. why is using @FindBy better than just declaring your element objects as By's? as in, By btn_logIn = By.id("login"); Seems that this code would be cleaner and result in fewer errors (stale element).

    ReplyDelete
  4. hi i am obul reddy,
    for this code can we add any thing in xml file?

    ReplyDelete
  5. Selenium is not just a single tool or a utility, rather a package of several testing tools and for the same reason it is referred to as a Suite. This blog gives great view for selenium beginners. Learn Selenium from the best Selenium Online Training in your locality at CatchExperts.com

    ReplyDelete
  6. dude its little difficult to read the code in plain text, you are giving great stuff but little problem in presentation, try to use any plugin which shows the code in actually coding format...thanks for the explanation on POM

    ReplyDelete
  7. working with page factory and webdriver is good topic and it plays the key role in selenium. explantion is very good. Selenium Online Training

    ReplyDelete
  8. Thanks for appreciating. Really means and inspires a lot to hear from you guys.I have bookmarked it and I am looking forward to reading new articles. Keep up the good work..Believe me, This is very helpful for me.

    Selenium Training in Chennai

    ReplyDelete
  9. Selenium training in Chennai
    We provide best selenium training in Chennai with real time scenarios.For real time training reach us 8122241286 and become experts in selenium.
    selenium training in chennai

    ReplyDelete
  10. It was very nice blog to learn about Selenium. Thanks for sharing new things... Selenium Training in Chennai

    ReplyDelete
  11. What you have written in this post is exactly what I have experience when I first started my blog.I’m happy that I came across with your site this article is on point,thanks again and have a great day.Keep update more information.
    Selenium Training in Chennai

    ReplyDelete
  12. Advanced Selenium post was nice keep updating thank u.
    Oracle training in marathahalli

    ReplyDelete
  13. Your new valuable key points imply much a person like me and extremely more to my office workers. With thanks; from every one of us.

    Hadoop Training in Chennai
    Hadoop Training in Bangalore
    Big data training in tambaram
    Big data training in Sholinganallur
    Big data training in annanagar

    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.
    Devops Training in Chennai

    Devops Training in Bangalore

    Devops Training in pune

    ReplyDelete
  15. After reading your post I understood that last week was with full of surprises and happiness for you. Congratz! Even though the website is work related, you can update small events in your life and share your happiness with us too.
    python training institute in chennai
    python training in Bangalore
    python training in pune
    python online training

    ReplyDelete
  16. This is my 1st visit to your web... But I'm so impressed with your content. Good Job!
    AWS Training in chennai
    AWS Training in bangalore

    ReplyDelete
  17. Its really an Excellent post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog. Thanks for sharing....
    Python training in marathahalli
    Python training in pune
    AWS Training in chennai

    ReplyDelete
  18. It seems you are so busy in last month. The detail you shared about your work and it is really impressive that's why i am waiting for your post because i get the new ideas over here and you really write so well.
    java training in chennai | java training in bangalore

    java online training | java training in pune

    ReplyDelete
  19. Well done! Pleasant post! This truly helps me to discover the solutions for my inquiry. Trusting, that you will keep posting articles having heaps of valuable data. You're the best! 
    Blueprism training in tambaram

    Blueprism training in annanagar

    Blueprism training in velachery

    ReplyDelete
  20. I found this informative and interesting blog so i think so its very useful and knowledge able.I would like to thank you for the efforts you have made in writing this article.
    Data Science course in kalyan nagar | Data Science course in OMR
    Data Science course in chennai | Data science course in velachery
    Data science online course | Data science course in jaya nagar

    ReplyDelete
  21. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.

    java training in chennai | java training in bangalore

    java online training | java training in pune

    ReplyDelete
  22. Outstanding blog thanks for sharing such wonderful blog with us ,after long time came across such knowlegeble blog. keep sharing such informative blog with us.
    Airport Management Courses in Chennai | Airport Management Training in Chennai | Airline Courses in Chennai | Airport Courses in Chennai | Airline and Airport Management Courses in Chennai

    ReplyDelete
  23. This comment has been removed by the author.

    ReplyDelete
  24. Nice information thank you,if you want more information please visit our link selenium Online Training Hyderabad

    ReplyDelete
  25. The blog is well written and Java is one of the widely accepted language. The reason is it's features and it is platform independent.
    Advanced JAVA Training
    JAVA Training Classes
    Core JAVA Certification
    JAVA Language Course
    Core JAVA Course

    ReplyDelete
  26. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us. expecting for your.
    German language training in chennai
    German Training in Chennai
    german classes chennai
    german teaching institutes in chennai
    German Training Institutes in Chennai
    German Training Chennai

    ReplyDelete
  27. Nice post. I learned some new information. Thanks for sharing.

    Article submission sites

    Education

    ReplyDelete
  28. This is an awesome post. Really very informative and creative contents. These concept is a good way to enhance the knowledge. Java Training in Chennai | Blue prism Training in Chennai

    ReplyDelete
  29. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.


    AWS Training in BTM Layout |Best AWS Training in BTM Layout

    AWS Training in Marathahalli | Best AWS Training in Marathahalli

    ReplyDelete
  30. Thanks For Your valuable posting, it was very informative

    toorizt
    Guest posting sites

    ReplyDelete
  31. Brilliant ideas that you have share with us.It is really help me lot and i hope it will help others also.
    update more different ideas with us.
    angularjs classes in bangalore
    angularjs tutorial in bangalore
    AngularJS Training in Ambattur
    AngularJS Courses in T nagar

    ReplyDelete
  32. Just stumbled across your blog and was instantly amazed with all the useful information that is on it. Great post, just what i was looking for and i am looking forward to reading your other posts soon!

    angularjs-Training in pune

    angularjs-Training in chennai

    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    ReplyDelete
  33. Thanks for the great post on your blog, it really gives me an insight on this topic.I must thank you for this informative ideas. I hope you will post again soon.
    vmware training in chennai
    vmware Training in Anna Nagar
    vmware training in chennai
    vmware Training in T nagar

    ReplyDelete
  34. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    python course in pune
    python course in chennai
    python Training in Bangalore

    ReplyDelete
  35. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.

    rpa training in chennai |best rpa training in chennai|
    rpa training in bangalore | best rpa training in bangalore

    ReplyDelete
  36. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.

    rpa training in chennai |best rpa training in chennai|
    rpa training in bangalore | best rpa training in bangalore

    ReplyDelete
  37. Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.

    Java training in Chennai

    Java training in Bangalore

    Java online training

    Java training in Pune

    ReplyDelete
  38. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  39. Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.
    Java Training in Chennai | Best Java Training in Chennai
    C C++ Training in Chennai | Best C C++ Training in Chennai

    Web Designing Training in Chennai | Best Web Designing Training in Chennai

    ReplyDelete
  40. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. 
    iphone display replacement service in chennai | iphone service center in chennai | iphone unlocking service in chennai | Authorized iphone service center in Chennai | iphone service center in chennai

    ReplyDelete
  41. This comment has been removed by a blog administrator.

    ReplyDelete
  42. You’d outstanding guidelines there. I did a search about the field and identified that very likely the majority will agree with your web page.
    Brij Univesity BCOM TimeTable 2020
    DAVV BCOM TimeTable 2020

    ReplyDelete
  43. Sharing the same interest, Infycle feels so happy to share our detailed information about all these courses with you all! Do check them out
    oracle training in chennai & get to know everything you want to about software trainings

    ReplyDelete
  44. Learn Amazon Web Services for making your career as a shining sun with Infycle Technologies. Infycle Technologies is the best AWS training centre 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 Python, AWS, 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, 200% placement assurance will be given here. To have the best career, call 7502633633 to Infycle Technologies and grab a free demo to know more.Best AWS Training in Chennai

    ReplyDelete
  45. hi thanku so much this infromation thanku so much
    Wordpress
    milesweb-review

    ReplyDelete
  46. Are You Aware Of Fxtm Review Minimum Deposit And Withdrawal Amounts?

    ReplyDelete
  47. Actually I read it yesterday but I had some thoughts about it and today I wanted to read it again because it is very well written. data science course in mysore

    ReplyDelete

Post a Comment

Popular Posts