В этой статье речь пойдет о следующих темах Java в привязке с Selenium Webdriver:
1) Модификаторы доступа
2) Работа с методами
3) Перегрузка методов
4) Передача аргументов методу
5) Возвращаемые значения
6) Статические свойства и методы
Нам понадобятся следующие классы:

Класс GoogleHomePage имеет следующий код:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
package classesandobjects; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class GoogleHomePage { // instance variable with private access specifier private static final String TEST_NAME = "Google Tests With Selenium"; // constant private By searchBox = By.name("q"); private By searchButton = By.cssSelector("button[name='btnK']"); // static access to static member public static String getTestName() { return TEST_NAME; } // getter access to private instance variable public By getSearchBox() { return searchBox; } public By getSearchButton() { return searchButton; } public void search(final FirefoxDriver firefoxDriver, final String searchTerm) { System.out.println("###################################"); System.out.println("###################################"); System.out.println("Search using string search term: " + searchTerm); firefoxDriver.findElement(getSearchBox()).clear(); firefoxDriver.findElement(getSearchBox()).sendKeys(searchTerm); } // overloaded methods public void search(final FirefoxDriver firefoxDriver, final int searchTerm) { System.out.println("###################################"); System.out.println("###################################"); System.out.println("Search using int search term: " + searchTerm); firefoxDriver.findElement(getSearchBox()).clear(); firefoxDriver.findElement(getSearchBox()).sendKeys(String.valueOf(searchTerm)); } // overloaded method with variable arguments public void search(final FirefoxDriver firefoxDriver, final String... searchTerm) { System.out.println("###################################"); System.out.println("###################################"); System.out.println("Search using multiple data sets"); WebElement searchTextBox = firefoxDriver.findElement(getSearchBox()); for (String testData : searchTerm) { System.out.println("Test Data: " + testData); firefoxDriver.findElement(getSearchBox()).clear(); searchTextBox.sendKeys(testData); } } // method with return type public String getSearchButtonLabel(final FirefoxDriver firefoxDriver) { String buttonLabel = firefoxDriver.findElement(getSearchButton()).getText(); return buttonLabel; } } |
Класс GoogleSearchResultPage:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package classesandobjects; import org.openqa.selenium.firefox.FirefoxDriver; public class GoogleSearchResultPage { private FirefoxDriver firefoxDriver; // Constructor public GoogleSearchResultPage(final FirefoxDriver firefoxDriver) { this.firefoxDriver = firefoxDriver; } private static String testData1; private static String testData2; static { testData1 = "software testing"; testData2 = "performance testing"; } public static String getTestData1() { return testData1; } public static String getTestData2() { return testData2; } } |
Класс TestClass вызова главного метода main():
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
package testclasses.classesandobjects; import classesandobjects.GoogleHomePage; import classesandobjects.GoogleSearchResultPage; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class TestClass { public static void main(final String[] args) { FirefoxDriver firefoxDriver = new FirefoxDriver(); firefoxDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); firefoxDriver.get("http://www.google.com/"); GoogleHomePage googleHomePage = new GoogleHomePage(); System.out.println("###########################"); System.out.println("###########################"); System.out.println("Test Name is: " + GoogleHomePage.getTestName()); // search using different data types googleHomePage.search(firefoxDriver, "Selenium HQ"); googleHomePage.search(firefoxDriver, 123); // search using variable argument String[] strArray = new String[3]; strArray[0] = "Firefox Webdriver"; strArray[1] = "Chrome Webdriver"; strArray[2] = "IE Webdriver"; googleHomePage.search(firefoxDriver, strArray); System.out.println("###################################"); System.out.println("###################################"); System.out.println("Get back to google home page"); firefoxDriver.get("http://www.google.com/"); String buttonLabel = googleHomePage.getSearchButtonLabel(firefoxDriver); System.out.println("return value is: " + buttonLabel); GoogleSearchResultPage googleSearchResultPage = new GoogleSearchResultPage(firefoxDriver); System.out.println("###########################"); System.out.println("###########################"); System.out.println("Test Data 1 is: " + GoogleSearchResultPage.getTestData1()); System.out.println("Test Data 2 is: " + GoogleSearchResultPage.getTestData2()); firefoxDriver.close(); firefoxDriver.quit(); } } |
Об модификаторах доступа можно прочесть в официальной документации Java. Я обращу внимание только объявление переменных первого класса:
|
1 2 3 |
private static final String TEST_NAME = "Google Tests With Selenium"; // constant private By searchBox = By.name("q"); private By searchButton = By.cssSelector("button[name='btnK']"); |
Они private потому, чтобы иметь к ним доступ только с класса GoogleHomePage. Это самый простой пример инкапсуляции.
Чтобы иметь доступ к этим переменным создаются методы типа By, которые возвращают эти переменные.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// static access to static member public static String getTestName() { return TEST_NAME; } // getter access to private instance variable public By getSearchBox() { return searchBox; } public By getSearchButton() { return searchButton; } |
Рассмотрите методы search. Все они имеют разную сигнатуру – параметры на входе,- это и есть пример перегрузки методов.
Во втором классе GoogleSearchResultPage следует обратить внимание на конструктор:
|
1 2 3 |
public GoogleSearchResultPage(final FirefoxDriver firefoxDriver) { this.firefoxDriver = firefoxDriver; } |
Когда в последнем классе TestClass мы создаем объект класса GoogleSearchResultPage именно он и вызывается.
Также рассмотрим свойство static.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
static { testData1 = "software testing"; testData2 = "performance testing"; } public static String getTestData1() { return testData1; } public static String getTestData2() { return testData2; } |
Самая главная особенность статических свойст и методов,-это их вызов с указанием названия класса и “.”. Наример, как это сделано в классе TestClass:
|
1 2 |
System.out.println("Test Data 1 is: " + GoogleSearchResultPage.getTestData1()); System.out.println("Test Data 2 is: " + GoogleSearchResultPage.getTestData2()); |
Запустив класс TestClass можно получить результат работы.