开发者

Can I improve on my wrapper method?

开发者 https://www.devze.com 2023-03-24 17:00 出处:网络
While using Selenium 2, I have开发者_如何学C following statements scattered in test methods - driver.findElement(By.name(usernameBox)).sendKeys(userEmailAddress);

While using Selenium 2, I have开发者_如何学C 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?


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.


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.


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..

0

精彩评论

暂无评论...
验证码 换一张
取 消