简体   繁体   中英

Can I make the WebDrivers as global variables in Java

I want to create a class where I set all the common actions of the WebDrivers such as: waitExplicit, findElement, click. But if I create a method then I have to create the WebDriver and WebDriverWait over and over on each method of the class, I already tried having a class for the Drivers, but when I call the methods, they just create instances over and over, so multiple windows open, I tried this way, but still cannot get to it:

public class AutomationActions{
    
    static LoadProperties prop = new LoadProperties(); //This class has the System.setProperty for the driver
    prop.getSysProp(); //***This is the issue, how can I solve this?****
    WebDriver driver = new ChromeDriver(); //this will not work without the one above working
    WebDriverWait wait = new WebDriverWait(driver, 30);//this will not work without the one above working

    public void waitForPageToLoad() throws Exception {
        ExpectedCondition<Boolean> pageLoadCondition = new
                ExpectedCondition<Boolean>() {
                    public Boolean apply(WebDriver driver) {
                        return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
                    }
                };
//        WebDriverWait wait = new WebDriverWait(driver, 30); // I want to avoid having to set this in every method
        wait.until(pageLoadCondition); //this is supposed to replace the line of code above
        
    }

I don't really work on Java much any more, I've written our framework in C# but I put together some quick classes in Java to show you how I set things up. I use page object model and I recommend you do too so I've written this example using page object model. I've written a simple test that uses Dave Haeffner's (one of the Selenium contributors) demo site, http://the-internet.herokuapp.com .

The basic concepts are:

  1. There is a class BaseTest that holds things that correspond to tests, eg setting up the driver at the start of the test, quitting the driver at the end of the test, etc. All of your tests will inherit from BaseTest

  2. There is a class BasePage that holds things that correspond to generic methods for finding elements, clicking on elements, etc. Each of your tests inherit from BasePage . (This is what I think the main part of your question is asking about).

  3. To follow the page object model, each page (or part of a page) is its own class and holds all locators and actions done on that page. For example, a simple login page would have the locators for username, password, and the login button. It would also hold a method Login() that takes a String username and a String password, enters those in the appropriate fields and clicks the Login button.

  4. The final class of this example is a sample test aptly named SampleTest .

  5. You shouldn't have any FindElements() or related calls in your tests, all those should be in the appropriate page object.

  6. This is using TestNG as the unit test library. Use it or JUnit, your preference but if you use JUnit, you will need to change the asserts and the annotations.

Under 'src', I create a folder for page objects, 'PageObjects', and a folder for tests, 'Tests'. Here's what the files look like on disk.

\src  
  \PageObjects
    BasePage.java
    DropdownListPage.java
  \Tests
    BaseTest.java
    SampleTest.java

BasePage.java

package PageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class BasePage
{
    private WebDriver driver;

    private final int shortWait = 10;

    public BasePage(WebDriver _driver)
    {
        driver = _driver;
    }

    public void ClickElement(By locator)
    {
        new WebDriverWait(driver, shortWait).until(ExpectedConditions.elementToBeClickable(locator)).click();
    }

    public WebElement FindElement(By locator)
    {
        return new WebDriverWait(driver, shortWait).until(ExpectedConditions.presenceOfElementLocated(locator));
    }

    // add more methods
}

DropdownListPage.java

package PageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;

public class DropdownListPage extends BasePage
{
    private final By dropdownListLocator = By.id("dropdown");

    public DropdownListPage(WebDriver _driver)
    {
        super(_driver);
    }

    public String GetSelectedOption()
    {
        return new Select(FindElement(dropdownListLocator)).getFirstSelectedOption().getText();
    }

    public void SelectOptionByIndex(int index)
    {
        new Select(FindElement(dropdownListLocator)).selectByIndex(index);
    }
}

BaseTest.java

package Tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;

public class BaseTest
{
    public WebDriver driver;

    public WebDriver GetChromeDriver()
    {
        System.setProperty("webdriver.chrome.driver", "C:\\Path\\To\\Chrome\\Driver\\chromedriver.exe");

        return new ChromeDriver();
    }

    @BeforeTest
    public void Setup()
    {
        driver = GetChromeDriver();
        driver.manage().window().maximize();
        driver.get("http://the-internet.herokuapp.com/dropdown");
    }

    @AfterTest
    public void Teardown()
    {
        driver.close();
    }
}

SampleTest.java

package Tests;

import org.testng.Assert;
import org.testng.annotations.Test;

import PageObjects.DropdownListPage;

public class SampleTest extends BaseTest
{
    @Test
    public void SampleTestCase()
    {
        DropdownListPage dropdownListPage = new DropdownListPage(driver);
        dropdownListPage.SelectOptionByIndex(1);
        Assert.assertEquals(dropdownListPage.GetSelectedOption(), "Option 1", "Verify first option was selected");
    }
}

You will need to create a project that contains Selenium for Java and TestNG. Download them and put them on your build path. Create the folder structure as described above and create each of these classes and copy/paste the contents into them. Now all you need to do is run SampleTest as a TestNG Test and it should go.

The test creates a new Chromedriver instance, navigates to the sample page, selects the first option in the dropdown, asserts that the dropdown text is correct, and then quits the driver.

That should get you started. There's a lot of info crammed into the above wall of text, let me know if you have some questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM