Reputation: 3496
While using Selenium 2, I have following statements scattered in test methods -
driver.findElement(By.name(usernameBox)).sendKeys(userEmailAddress);
I think of abstracting them in static methods of a WebUtil class -
public class WebUtils {
public static void type(WebDeriver driver, String locator, String testData) {
driver.findElement(By.name(locator)).sendKeys(testData);
}
}
And the method call would be -
WebUtils.type(driver, usernameBox, userEmailAddress);
Could I improve it more, for example if I could avoid passing driver object every time, or some thing more?
Upvotes: 0
Views: 444
Reputation: 15579
I would suggest you extend the base class that you generally use and add your extension methods there.
here is an example to extend Selenium class.
public class MySelenium : WebDriverBackedSelenium
{
public IWebDriver Driver { get; set; }
public ISelenium Selenium { get; set; }
public MySelenium(IWebDriver baseDriver, string baseUrl)
: base(baseDriver, baseUrl)
{
Driver = baseDriver;
}
public MySelenium(IWebDriver baseDriver, Uri baseUrl)
: base(baseDriver, baseUrl) { }
public static void type(String locator, String testData) {
Driver.findElement(By.name(locator)).sendKeys(testData);
}
}
You initialize it as follows in a common class that is used by all your tests:
var driver =GetDriver(); //method to initialize driver
Selenium= new MySelenium(driver,baseUrl); //Selenium is a protected variable accessible from your tests
Now you invoke type as follows:
Selenium.type(userNameBox,"username");
P.S: Srry the above code is in c# but you can port it over to java..
Upvotes: 0
Reputation: 12496
I actually prefer the fluent interface of the original example.
I was wrong, WebElement doesn't have a fluent interface. sendKeys
returns void
. Still though, a static wrapper over the original interface seems unnecessary.
Upvotes: 1
Reputation: 15109
If the WebDriver is going to be the same every time then you could make it part of the WebUtils class like so:
private final static WebDriver driver = new WebDriver();
and then use:
public class WebUtils {
public static void type(String locator, String testData) {
driver.findElement(By.name(locator)).sendKeys(testData);
}
}
That is the only optimization I can see.
Upvotes: 1