Use an Abstract class. I have our entire login procedure in an abstract class and just call that method as the first thing in my test. If any credentials need to be changed, you only need to change them in one place.
The method in my abstract class:
protected void getBaseURLAndLoginTestUser() throws Exception
{
driver.get(BASE_URL);
assertEquals("some text here", findElementBySelector("h3").getText());
WebElement userName = findElementById("j_username");
userName.clear();
userName.sendKeys("testing1");
WebElement password = findElementById("j_password");
password.clear();
password.sendKeys("testing1");
WebElement loginButton = findElementById("modalDialogButton");
loginButton.click();
}
Which is then used in another method in my abstract:
protected void setup() throws Exception
{
getBaseURLAndLoginTestUser();
WebElement selectRole = findElementByXpath("//div[@id='selectRoles']/ul/li[text()='loginRole (Dept C)']");
selectRole.click();
Thread.sleep(2000);
WebElement continueButton = findElementById("continue");
continueButton.click();
Thread.sleep(2500);
assertEquals("some text here", findElementBySelector("header.container_12.clearfix > h1").getText());
String destinationUrl = navigateToUrl(getNavigationUrl());
driver.get(destinationUrl);
}
And FINALLY, all you see in my test class is:
public class NameOfClass extends AbstractClass
{
@Override
@BeforeClass
public void setup() throws Exception
{
super.setup();
}
I have to use super because I change the URL I am navigating to, which is contained in another abstract class.