Creating a common import statement for commonly used imports


  • QA Engineer

    import java.util.Properties;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    

    I have a page object model and each page object requires these import statements. It's a hectic task to write the import statement repeatedly for each class file.

    Is there a way to reduce line of code and import or use the commonly used imports, by using a single line of code like:

    import package.commonlyusedimports;
    

    Were commonlyusedimports class is defined as:

    package xxx;
    import java.util.Properties;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    
    public class commonlyusedimports{
    
    }
    

    Note: I tried inheritance, even then parent class imports are not visible to child.



  • You can inject a factory for the behaviors you need from the packages you are importing*

    public interface WebFactory {
    
       public Element findElement(Locator loc);
       ....
    }
    

    The imports would be interfaces as well...

    public interface Element {
        public String getText();
        ...
    }
    

    And then you can implement these interfaces by biding to Selenium however you want.

    public class SeleniumElement implements Element{
            public String getText() {
            ...
            }
    }
    

    And then implementing the factory:

    public class SeleniumWebFactory implements WebFactory {
    
       public Element findElement(Locator loc) {
          ....
       }
    }
    

    In the end, you just need to inject a factory to your page objects:

    @BeforeSuite
    ....
    
    this.factory = new SeleniumWebFactory();
    
    @Test()
    ....
    Page page = new Page(this.factory)
    

    This way, the page object can call for generic behavior such as WebFactory.findElement and Element.getText without explicitly requiring them.

    * Which is a good practice, because currently you are binding all your code to Selenium. You can invert this dependency, so that Selenium would be unable to screw you.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2