In this article i will try to show you how to user PageFactory of webdriver.
1. Declare a class having webelement fields.
public class GooglePage
{
WebElement q; //q should be either name or id of the locator.
void search()
{
q.sendeys("this is webdriver");
q.submit();
}
}
2. Initialize above class other wise q will throw null pointer exception
public class GoogleSearch
{
public static void main(String []arg )
{
WebDriver driver=new FirefoxDriver()
driver.get("http://www.google.com");
GooglePage gp=PageFactory.initElements(driver,GooglePage.class);
gp.search();
}
}
* GooglePage gp=PageFactory.initElements(driver,GooglePage.class); : This line will initilize the q object of GooglePage.
You can rewrite above GooglePage class by using @FindBy annotation. Using annotation you can specify which locating technique you are using , it could be complex xpath,name,id...etc. The example is below:
public class GooglePage
{
@FindBy(how=How.xpath,using="//input[@name='q']")
WebElement googleSearchElement;
void search()
{
googleSearchElement.sendeys("this is webdriver");
googleSearchElement.submit();
}
}
1. Declare a class having webelement fields.
public class GooglePage
{
WebElement q; //q should be either name or id of the locator.
void search()
{
q.sendeys("this is webdriver");
q.submit();
}
}
2. Initialize above class other wise q will throw null pointer exception
public class GoogleSearch
{
public static void main(String []arg )
{
WebDriver driver=new FirefoxDriver()
driver.get("http://www.google.com");
GooglePage gp=PageFactory.initElements(driver,GooglePage.class);
gp.search();
}
}
* GooglePage gp=PageFactory.initElements(driver,GooglePage.class); : This line will initilize the q object of GooglePage.
You can rewrite above GooglePage class by using @FindBy annotation. Using annotation you can specify which locating technique you are using , it could be complex xpath,name,id...etc. The example is below:
public class GooglePage
{
@FindBy(how=How.xpath,using="//input[@name='q']")
WebElement googleSearchElement;
void search()
{
googleSearchElement.sendeys("this is webdriver");
googleSearchElement.submit();
}
}
I am getting the below error by saying nosuchelement found. Can you help me out.
ReplyDeleteException in thread "main" org.openqa.selenium.NoSuchElementException: Unable to find element with id == txtUserID (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 291 milliseconds