Thursday, July 15, 2010

Get WebElement within PageFactory class by refelction

I just wandering how to get PageFactory's private WebElements in another test method?
Here is the code which Vance Zhao provided a way to find WebElements by reflection:


......
FSILoginPage landingpage =
PageFactory.initElements(driver, LoginPage.class);

Field f = landingpage.getClass().getDeclaredField("username");

WebElement e = new DefaultElementLocator(driver, f).findElement();

e.sendKeys("123456");
.....


Here is the PageObjects code:

public class LoginPage {

private WebElement username;
......


I will not consider to do this kind of coding in our test code , it is really a “Demo code”.

I will try to Abstract public methods in PageObjects Class which is a really worth stuff to do and make testing more fun and challenging! And also consider make WebElement to public as a workaround :)

1 comment:

  1. Hi,
    I think this is useful to find all webelements associated with @FindBy annotation. You could probably write a wrapper class and write some utility functions in that class such as "are all of my webelements correct in the pagefactory class", "are they displayed on the page". These methods can then be used as like "sanity" tests for the pages. You would know the state of the page before even the services in the pages are run and you get earlier feedback.

    I am curious to know why you think such an approach is not ideal.

    ReplyDelete