Reputation: 25
I am writing a login function, I want this function to exit gracefully in case of an error/unexpected condition.example: when I enter the password, if the text field has changed/not present I want the function to exit with the message saying that password field is not present. the function status should be "Fail" and the exact failure message. same way it should handle any other exception that might occur. What is the right way to right this function, so that I can follow this practice in the future functions that I write that deals with web objects?
public boolean Login(String userName, String password, String url)
{
_driver= new FirefoxDriver();
_driver.manage().window().maximize();
_driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
_driver.get(url);
_driver.findElement(By.Xpath(".//*[id='usename']")).sendKeys(userName);
_driver.findElement(By.Xpath(".//*[id='pword']")).sendKeys(password);
_driver.findElement(By.Xpath(".//*[id='btn']")).click();
String title = _driver.getTitle();
boolean pass;
if (title.toLowerCase().contains("homepage"))
{
pass=true;
}
else
{
Assert.fail("Manager home page not opened after login");
pass=false;
}
return pass;
}
Upvotes: 0
Views: 50
Reputation: 25644
You would want to remove the driver setup and navigating to the initial URL from your function. Your function should only log in... to match the name, Login()
. If you want to use the page object model, you would do something like
The main script would look like
_driver = new FirefoxDriver();
_driver.manage().window().maximize();
_driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
_driver.get(url);
LoginPage loginPage = new LoginPage(_driver);
loginPage.Login(userName, password);
Assert.assertTrue(_driver.getTitle().contains("homepage"), "Log in successful");
While the LoginPage class would look like
public class LoginPage
{
WebDriver _driver;
public LoginPage(WebDriver driver)
{
_driver = driver;
}
public void Login(String userName, String password)
{
_driver.findElement(By.id("usename")).sendKeys(userName);
_driver.findElement(By.id("pword]")).sendKeys(password);
_driver.findElement(By.id("btn")).click();
}
}
BTW, I changed your locators to use By.id()
instead of XPath. You should avoid using XPath unless it's absolutely necessary... finding an element by containing text, etc. Start with By.id()
then use By.cssSelector()
... if those two won't work, then fall back to XPath. XPath is slower, more likely to be brittle, and has inconsistent support in browsers.
Upvotes: 1