Skip to main content

Command Palette

Search for a command to run...

java selenium WRT framework

Published
•17 min read•View as Markdown

Java's Utilization in a Selenium Automation Framework (Topic-Wise)

This guide organizes Java's role by core programming concepts, demonstrating their practical application in building robust and scalable Selenium WebDriver automation frameworks.

1. Core Java Fundamentals

These are the absolute basics, forming the bedrock of all your automation scripts.

  • 1.1 Data Types and Variables

    • Java Concept: Primitives (int, boolean, double, char), and Non-primitives (String, Object, Arrays, Classes, Interfaces). Variables are named storage locations.

    • Utilization in Selenium:

      • String: Most common. Used for storing locators (String xpath = "//input[@id='username']";), URLs (String appUrl = "https://www.example.com";), expected/actual text (String pageTitle = driver.getTitle();), test data (usernames, passwords).

      • boolean: Used for conditional checks and assertions (boolean isElementDisplayed = element.isDisplayed();).

      • int / long: For numerical values like counts (int numberOfLinks = links.size();), timeouts (long timeoutSeconds = 10;).

      • WebDriver (Interface Type): Declaring the browser instance (WebDriver driver;).

      • WebElement (Interface Type): Storing references to UI elements (WebElement loginButton;).

    • Example: Java

        public class MyTest {
            WebDriver driver; // WebDriver (interface)
            String baseUrl = "https://www.google.com"; // String
            int waitTime = 15; // int for seconds
            boolean isLogoVisible = false; // boolean
      
            @Test
            public void testMethod() {
                driver.get(baseUrl);
                WebElement searchBox = driver.findElement(By.name("q")); // WebElement
                searchBox.sendKeys("Selenium Java"); // String parameter
                isLogoVisible = driver.findElement(By.id("logo")).isDisplayed(); // boolean assignment
            }
        }
      
  • 1.2 Operators

    • Java Concept: Arithmetic (+, -, *, /), Relational (==, !=, <, >), Logical (&&, ||, !), Assignment (=, +=), Unary (++, --).

    • Utilization in Selenium:

      • Relational/Equality: Comparing actual vs. expected values in assertions (Assert.assertEquals(actualTitle, expectedTitle);), checking element presence or state (if (driver.findElements(By.id("element")).size() > 0)).

      • Logical: Combining multiple conditions (if (element.isDisplayed() && element.isEnabled())).

      • Assignment: Assigning values to variables (driver = new ChromeDriver();, String text = element.getText();).

    • Example: Java

        @Test
        public void verifyLoginPageElements() {
            driver.get("https://www.example.com/login");
            boolean usernameFieldPresent = driver.findElements(By.id("username")).size() > 0;
            boolean passwordFieldPresent = driver.findElements(By.id("password")).size() > 0;
      
            // Logical AND
            if (usernameFieldPresent && passwordFieldPresent) {
                System.out.println("Both username and password fields are present.");
            } else {
                System.out.println("One or both fields are missing.");
            }
      
            // Equality for verification
            String currentUrl = driver.getCurrentUrl();
            if (currentUrl.equals("https://www.example.com/login")) {
                System.out.println("Successfully on login page.");
            }
        }
      
  • 1.3 Control Flow Statements (Conditional & Looping)

    • Java Concept: if-else, switch for decision making; for, while, do-while, for-each for repetition.

    • Utilization in Selenium:

      • if-else:

        • Handling dynamic UI elements (e.g., pop-ups, optional elements).

        • Executing different actions based on test data.

        • Performing conditional assertions.

        • Choosing browser based on config: if (browserName.equalsIgnoreCase("chrome")) { ... } else { ... }

      • for / for-each:

        • Iterating through lists of web elements (e.g., all links, all products on a page).

        • Reading data from external data sources (e.g., rows in an Excel sheet).

        • Performing actions multiple times.

      • while: Implementing custom waits (less common than explicit waits, but possible for retry logic).

    • Example: Java

        @Test
        public void handleDynamicPopUpAndProcessLinks() {
            driver.get("https://www.example.com");
      
            // Conditional check for a pop-up
            if (driver.findElements(By.id("welcome-popup")).size() > 0) {
                driver.findElement(By.id("welcome-popup-close")).click();
                System.out.println("Closed welcome pop-up.");
            } else {
                System.out.println("No welcome pop-up displayed.");
            }
      
            // Loop through all links on the page
            List<WebElement> allLinks = driver.findElements(By.tagName("a"));
            System.out.println("Total links: " + allLinks.size());
            for (WebElement link : allLinks) { // for-each loop
                String href = link.getAttribute("href");
                String text = link.getText();
                if (!text.isEmpty()) { // Conditional inside loop
                    System.out.println("Link Text: " + text + ", URL: " + href);
                }
            }
        }
      
  • 1.4 Arrays

    • Java Concept: Fixed-size, ordered collections of elements of the same data type.

    • Utilization in Selenium:

      • Storing a pre-defined set of test data (e.g., multiple search keywords).

      • Less frequently used for dynamic lists of WebElements compared to List.

    • Example: Java

        @Test
        public void searchMultipleProducts() {
            String[] products = {"Laptop", "Mouse", "Keyboard"};
            WebElement searchBox = driver.findElement(By.id("search-input"));
            WebElement searchButton = driver.findElement(By.id("search-button"));
      
            for (String product : products) {
                searchBox.clear();
                searchBox.sendKeys(product);
                searchButton.click();
                Assert.assertTrue(driver.getTitle().contains(product), "Search failed for: " + product);
                driver.navigate().back(); // Go back for next search
                searchBox = driver.findElement(By.id("search-input")); // Relocate if page reloaded
                searchButton = driver.findElement(By.id("search-button"));
            }
        }
      

2. Object-Oriented Programming (OOP) Concepts

The bedrock of robust, maintainable, and scalable Selenium automation frameworks, especially with the Page Object Model.

  • 2.1 Classes and Objects (Encapsulation)

    • Java Concept: A class is a blueprint; an object is an instance. Encapsulation bundles data (fields) and methods acting on that data within a single unit, hiding internal implementation.

    • Utilization in Selenium:

      • Page Object Model (POM): Each web page is represented as a Java class (LoginPage, DashboardPage). Web elements are private fields (data), and interactions are public methods. This encapsulates UI details.

      • Test Classes: TestNG/JUnit test files are Java classes (LoginTest, ProductSearchTest).

      • Utility Classes: Common functions grouped into classes (ExcelReader, ScreenshotUtils, WebDriverFactory).

    • Example (POM): Java

        // com.example.pages.LoginPage.java
        package com.example.pages;
      
        import org.openqa.selenium.WebDriver;
        import org.openqa.selenium.WebElement;
        import org.openqa.selenium.support.FindBy;
        import org.openqa.selenium.support.PageFactory;
      
        public class LoginPage { // Class representing the Login Page
            private WebDriver driver; // Encapsulated data (WebDriver instance)
      
            // Encapsulated web elements (private fields)
            @FindBy(id = "username")
            private WebElement usernameField;
            @FindBy(id = "password")
            private WebElement passwordField;
            @FindBy(xpath = "//button[@type='submit']")
            private WebElement loginButton;
      
            // Constructor to initialize elements
            public LoginPage(WebDriver driver) {
                this.driver = driver;
                PageFactory.initElements(driver, this); // Initializes elements with @FindBy
            }
      
            // Public methods (behaviors) to interact with the page
            public void enterUsername(String username) {
                usernameField.sendKeys(username);
            }
      
            public void enterPassword(String password) {
                passwordField.sendKeys(password);
            }
      
            public HomePage clickLogin() {
                loginButton.click();
                return new HomePage(driver); // Returns a new page object
            }
        }
      
        // com.example.tests.LoginTest.java
        package com.example.tests;
      
        import com.example.pages.LoginPage;
        import com.example.pages.HomePage;
        // ... WebDriver and TestNG imports
      
        public class LoginTest {
            WebDriver driver;
      
            @BeforeMethod
            public void setup() { /* Initialize driver */ }
      
            @Test
            public void testSuccessfulLogin() {
                driver.get("https://yourwebsite.com/login");
                LoginPage loginPage = new LoginPage(driver); // Create LoginPage object
                loginPage.enterUsername("validuser");
                loginPage.enterPassword("validpass");
                HomePage homePage = loginPage.clickLogin(); // Interact via object methods
                Assert.assertTrue(homePage.isWelcomeMessageDisplayed());
            }
        }
      
  • 2.2 Methods (Functions)

    • Java Concept: Blocks of code that perform a specific task, can take parameters, and return values.

    • Utilization in Selenium:

      • All actions performed in your tests are encapsulated in methods: driver.get(), element.click(), loginPage.enterUsername().

      • TestNG methods are defined with @Test.

      • Setup/teardown logic is in @Before/@After methods.

      • Utility functions are in their own methods.

    • Example: (See LoginPage and LoginTest examples above for enterUsername, clickLogin, testSuccessfulLogin methods).

  • 2.3 Constructors

    • Java Concept: Special methods with the same name as the class, used to initialize objects when they are created.

    • Utilization in Selenium:

      • Page Object Initialization: Essential for passing the WebDriver instance to a page object, allowing it to interact with the browser.

      • Initializing any required services or dependencies for a class.

    • Example: (See LoginPage constructor in the Classes and Objects example above).

  • 2.4 Inheritance

    • Java Concept: A class (subclass) can inherit fields and methods from another class (superclass) using extends. Promotes code reuse and a hierarchical structure.

    • Utilization in Selenium:

      • BaseTest Class: Common practice to create a BaseTest class to encapsulate browser setup, teardown, and other common configurations. All specific test classes then extend BaseTest. This avoids code duplication across tests.

      • BasePage Class: An abstract BasePage can contain elements/methods common to all pages (e.g., header, footer, a getPageTitle() method). Specific page objects then extend this BasePage.

    • Example: Java

        // com.example.base.BaseTest.java
        package com.example.base;
        import org.openqa.selenium.WebDriver; // ... imports
        import org.testng.annotations.AfterMethod;
        import org.testng.annotations.BeforeMethod;
      
        public class BaseTest {
            protected WebDriver driver; // Protected for access by subclasses
      
            @BeforeMethod
            public void setupBrowser() {
                // Initialize WebDriver
                driver = new ChromeDriver();
                driver.manage().window().maximize();
                driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
            }
      
            @AfterMethod
            public void tearDownBrowser() {
                if (driver != null) {
                    driver.quit();
                }
            }
        }
      
        // com.example.tests.LoginTest.java
        package com.example.tests;
        import com.example.base.BaseTest; // Import BaseTest
        import com.example.pages.LoginPage; // ... imports
      
        public class LoginTest extends BaseTest { // Extends BaseTest
            // driver is inherited, setupBrowser/tearDownBrowser are inherited
      
            @Test
            public void testLoginScenario() {
                driver.get("https://yourwebsite.com/login");
                LoginPage loginPage = new LoginPage(driver); // Uses inherited driver
                // ... test steps
            }
        }
      
  • 2.5 Polymorphism

    • Java Concept: "Many forms." Allows objects of different classes to be treated as objects of a common superclass or interface. Achieved via method overloading (same name, different parameters) and method overriding (subclass redefines parent method).

    • Utilization in Selenium:

      • WebDriver Interface: The most prominent example. You declare WebDriver driver; and then instantiate it as new ChromeDriver(), new FirefoxDriver(), etc. This means your code interacts with the generic WebDriver interface, but the actual behavior changes based on the concrete browser driver object. This is crucial for cross-browser testing.

      • Method Overloading: A utility method to wait could be overloaded to accept different types of locators or elements: waitForElement(By locator) vs. waitForElement(WebElement element).

    • Example: Java

        public class BrowserManager {
            public static WebDriver getBrowser(String browserName) { // Polymorphism via interface
                if (browserName.equalsIgnoreCase("chrome")) {
                    return new ChromeDriver(); // ChromeDriver is a WebDriver
                } else if (browserName.equalsIgnoreCase("firefox")) {
                    return new FirefoxDriver(); // FirefoxDriver is a WebDriver
                } else {
                    throw new IllegalArgumentException("Unsupported browser: " + browserName);
                }
            }
      
            // Method Overloading example (hypothetical utility)
            public void waitFor(long seconds) { /* waits for N seconds */ }
            public void waitFor(WebElement element) { /* waits for element to be visible */ }
        }
      
  • 2.6 Abstraction

    • Java Concept: Hiding complex implementation details and showing only essential features. Achieved using abstract classes and interfaces.

    • Utilization in Selenium:

      • WebDriver Interface: Selenium itself is a prime example. When you call driver.click(), you don't need to know the specific native browser API calls happening under the hood; you just use the abstract click() method. This simplifies API usage.

      • Abstract BasePage: An abstract class BasePage can define common elements or methods that all page objects should have, but not necessarily implement concretely. It enforces a contract. Java

          // com.example.pages.AbstractBasePage.java
          public abstract class AbstractBasePage {
              protected WebDriver driver;
              public AbstractBasePage(WebDriver driver) { this.driver = driver; }
              public abstract String getPageTitle(); // Must be implemented by subclasses
              public void clickLogout() { /* common logout logic */ } // Concrete method
          }
        
          // com.example.pages.HomePage.java
          public class HomePage extends AbstractBasePage {
              public HomePage(WebDriver driver) { super(driver); }
              @Override
              public String getPageTitle() { return driver.getTitle(); } // Implementation
          }
        

3. Java Collections Framework

Essential for managing groups of elements and test data in your automation scripts.

  • 3.1 List (e.g., ArrayList)

    • Java Concept: Ordered collection that allows duplicate elements. ArrayList is a resizable array.

    • Utilization in Selenium:

      • driver.findElements(By.locator) returns a List<WebElement>, which is the most common use case.

      • Storing test data read from external sources (e.g., rows from a CSV or Excel).

      • Managing dropdown options.

    • Example: Java

        @Test
        public void verifyMenuItems() {
            driver.get("https://www.example.com/menu");
            List<WebElement> menuItems = driver.findElements(By.cssSelector(".menu-item")); // List of WebElements
            Assert.assertEquals(menuItems.size(), 5, "Incorrect number of menu items.");
      
            List<String> actualMenuItemTexts = new ArrayList<>(); // List of Strings
            for (WebElement item : menuItems) {
                actualMenuItemTexts.add(item.getText());
            }
            Assert.assertTrue(actualMenuItemTexts.contains("About Us"), "About Us not found in menu.");
        }
      
  • 3.2 Set (e.g., HashSet)

    • Java Concept: Unordered collection that does not allow duplicate elements.

    • Utilization in Selenium:

      • Handling Multiple Windows/Tabs: driver.getWindowHandles() returns a Set<String>, representing unique window/tab IDs. Using a Set ensures you don't process the same window twice.
    • Example: Java

        @Test
        public void handleNewWindow() {
            String originalWindow = driver.getWindowHandle();
            driver.findElement(By.id("openNewWindowButton")).click(); // Clicks a button that opens a new window
      
            Set<String> allWindowHandles = driver.getWindowHandles(); // Set of unique window IDs
      
            for (String handle : allWindowHandles) {
                if (!handle.equals(originalWindow)) {
                    driver.switchTo().window(handle); // Switch to the new window
                    break;
                }
            }
            Assert.assertTrue(driver.getTitle().contains("New Window Title"), "Did not switch to new window.");
            driver.close(); // Close the new window
            driver.switchTo().window(originalWindow); // Switch back
        }
      
  • 3.3 Map (e.g., HashMap)

    • Java Concept: Stores key-value pairs, where each key is unique.

    • Utilization in Selenium:

      • Storing Test Data: Reading data from external sources (e.g., Excel) and storing each row as a Map<String, String> where keys are column headers and values are cell data.

      • Configuration: Storing browser options or capabilities (e.g., ChromeOptions).

      • Test Parameters: Passing parameters to tests, though TestNG's @Parameters and testng.xml are more common for direct parameter injection.

    • Example: Java

        @Test
        public void testLoginWithCredentialsMap() {
            Map<String, String> credentials = new HashMap<>();
            credentials.put("username", "standard_user");
            credentials.put("password", "secret_sauce");
      
            driver.get("https://www.saucedemo.com");
            driver.findElement(By.id("user-name")).sendKeys(credentials.get("username"));
            driver.findElement(By.id("password")).sendKeys(credentials.get("password"));
            driver.findElement(By.id("login-button")).click();
            Assert.assertTrue(driver.getCurrentUrl().contains("inventory"), "Login failed.");
        }
      

4. Exception Handling

Crucial for making test automation scripts robust and preventing unexpected crashes, providing meaningful feedback on failures.

  • 4.1 try-catch-finally Block

    • Java Concept: try block for code that might throw an exception, catch block to handle specific exception types, finally block for code that always executes regardless of an exception (e.g., cleanup).

    • Utilization in Selenium:

      • Robust Element Interaction: Handling NoSuchElementException when an element might be conditionally present or not found.

      • Taking Screenshots on Failure: The finally block (or @AfterMethod in TestNG) is ideal for capturing screenshots even if a test step fails.

      • Resource Cleanup: Ensuring browser is closed (driver.quit()) even if errors occur during test execution.

    • Example: Java

        @Test
        public void testOptionalElementPresence() {
            driver.get("https://www.example.com");
            try {
                WebElement promoBanner = driver.findElement(By.id("promo-banner"));
                if (promoBanner.isDisplayed()) {
                    promoBanner.click();
                    System.out.println("Promo banner clicked.");
                }
            } catch (NoSuchElementException e) {
                System.out.println("Promo banner not found, continuing test.");
                // This is expected, so no Assert.fail() here
            } catch (Exception e) {
                // Catch any other unexpected exceptions
                System.err.println("An unexpected error occurred: " + e.getMessage());
                Assert.fail("Test failed due to unexpected error.");
            } finally {
                System.out.println("Execution for testOptionalElementPresence finished.");
                // Ensure driver.quit() is handled by AfterMethod for full cleanup.
            }
        }
      
  • 4.2 throws Keyword

    • Java Concept: Used in method signatures to declare that a method might throw one or more specified types of checked exceptions. This forces the calling method to either handle the exception (with try-catch) or re-declare it.

    • Utilization in Selenium:

      • File Operations: Methods that read/write files (e.g., for test data or reports) often declare throws IOException or FileNotFoundException.

      • Thread.sleep(): Requires throws InterruptedException.

    • Example: Java

        public class UtilityClass {
            // Method declares it might throw IOException
            public void readTestData(String filePath) throws IOException {
                FileInputStream fis = new FileInputStream(filePath);
                // ... logic to read from file
                fis.close();
            }
        }
      
        public class MyTest {
            @Test
            public void loadDataAndPerformTest() {
                UtilityClass utils = new UtilityClass();
                try {
                    utils.readTestData("data.csv");
                    // ... use loaded data in Selenium
                } catch (IOException e) {
                    System.err.println("Error reading test data: " + e.getMessage());
                    Assert.fail("Failed to load test data.");
                }
            }
        }
      

5. File I/O (Input/Output)

Essential for managing test data, configuration, and generating reports.

  • 5.1 Properties Class

    • Java Concept: A subclass of Hashtable (a Map implementation) used to maintain a list of key-value pairs, typically loaded from .properties files.

    • Utilization in Selenium:

      • Centralized Configuration: Storing environment-specific data (URLs, browser types), timeouts, test user credentials, API keys, report paths in config.properties files. This allows easy modification without recompiling code.
    • Example: Java

        // config.properties
        browser=chrome
        baseUrl=https://www.example.com
        defaultTimeout=10
      
        // In Java code:
        public class ConfigManager {
            private Properties prop;
      
            public ConfigManager() {
                prop = new Properties();
                try (FileInputStream fis = new FileInputStream("src/main/resources/config.properties")) {
                    prop.load(fis);
                } catch (IOException e) {
                    throw new RuntimeException("Failed to load config.properties", e);
                }
            }
      
            public String getBrowser() { return prop.getProperty("browser"); }
            public String getBaseUrl() { return prop.getProperty("baseUrl"); }
            public int getDefaultTimeout() { return Integer.parseInt(prop.getProperty("defaultTimeout")); }
        }
      
  • 5.2 Streams (FileInputStream, BufferedReader, BufferedWriter, etc.)

    • Java Concept: Provides mechanisms to read and write data from/to sources like files, network connections.

    • Utilization in Selenium:

      • Reading CSV/Text Data: For simple data-driven tests.

      • Generating Custom Logs/Reports: Writing test execution details or custom reports to text files.

    • Example: Java

        // Reading CSV for test data
        public List<String[]> readCsv(String filePath) throws IOException {
            List<String[]> data = new ArrayList<>();
            try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
                String line;
                while ((line = br.readLine()) != null) {
                    data.add(line.split(",")); // Split by comma
                }
            }
            return data;
        }
      
  • 5.3 External Libraries (e.g., Apache POI for Excel)

    • Java Concept: While not part of core Java, these are Java libraries built to extend Java's capabilities.

    • Utilization in Selenium:

      • Data-Driven Testing from Excel: Apache POI is the standard library for reading and writing Microsoft Excel files (.xlsx, .xls). This is extensively used with TestNG's @DataProvider to supply complex test data sets.

6. Generics

  • Java Concept: Allows writing type-safe code that can work with different types without type casting or runtime errors. Reduces ClassCastException.

  • Utilization in Selenium:

    • Collections: You constantly use generics with Java Collections to ensure type safety: List<WebElement>, Set<String>, Map<String, String>. This ensures that when you retrieve an element from a List<WebElement>, it's guaranteed to be a WebElement and not something else.

    • Custom Utilities: If you build generic helper methods that can operate on different types of data, generics are key.

    • Example: Java

        // Using generics in Selenium API
        List<WebElement> buttons = driver.findElements(By.tagName("button")); // List<WebElement>
        Set<String> windowHandles = driver.getWindowHandles(); // Set<String>
      
        // Custom generic utility
        public <T> T getFirstElement(List<T> list) {
            if (list != null && !list.isEmpty()) {
                return list.get(0);
            }
            return null;
        }
      
        @Test
        public void testGenericUsage() {
            List<String> names = Arrays.asList("Alice", "Bob");
            String firstPerson = getFirstElement(names); // Returns String
            Assert.assertEquals(firstPerson, "Alice");
      
            List<WebElement> images = driver.findElements(By.tagName("img"));
            WebElement firstImage = getFirstElement(images); // Returns WebElement
            Assert.assertNotNull(firstImage);
        }
      

7. Annotations (Primarily TestNG/JUnit)

  • Java Concept: Provide meta-data about program elements (classes, methods, fields). They start with @.

  • Utilization in Selenium:

    • TestNG/JUnit Test Organization: These are the backbone of how your tests are structured and executed.

      • @Test: Marks a method as an executable test case.

      • @BeforeSuite, @AfterSuite, @BeforeTest, @AfterTest, @BeforeClass, @AfterClass, @BeforeMethod, @AfterMethod: Define the execution lifecycle (setup/teardown at different levels).

      • @DataProvider: Links a method to provide test data to a @Test method (for data-driven testing).

      • @Parameters: Allows passing data from testng.xml to test methods.

      • @Listeners: For integrating custom logic (e.g., capturing screenshots on failure, custom logging) by implementing TestNG interfaces like ITestListener.

    • Selenium PageFactory:

      • @FindBy: Used in Page Object classes to specify locator strategies for WebElements, allowing PageFactory.initElements() to initialize them.
    • Example: (See LoginTest in Inheritance section, LoginPage in Classes and Objects section for TestNG and FindBy annotations).

8. Concurrency / Multi-threading (Advanced Performance)

  • Java Concept: Running multiple parts of a program simultaneously. Involves Thread class, Runnable interface, ExecutorService.

  • Utilization in Selenium:

    • Parallel Test Execution: Crucial for significantly reducing the execution time of large test suites. TestNG provides built-in support for parallel execution (parallel="methods", parallel="classes" in testng.xml).

    • ThreadLocal: Absolutely essential for managing WebDriver instances in parallel execution. Each thread needs its own independent WebDriver instance to prevent conflicts and ensure test isolation. ThreadLocal provides a way to store data that is unique to each thread.

    • Example (ThreadLocal for Parallel Execution): Java

        // com.example.driver.DriverManager.java
        public class DriverManager {
            private static ThreadLocal<WebDriver> driver = new ThreadLocal<>();
      
            public static WebDriver getDriver() {
                return driver.get();
            }
      
            public static void setDriver(String browserType) {
                WebDriver d;
                if (browserType.equalsIgnoreCase("chrome")) {
                    d = new ChromeDriver();
                } else if (browserType.equalsIgnoreCase("firefox")) {
                    d = new FirefoxDriver();
                } else {
                    throw new IllegalArgumentException("Browser not supported.");
                }
                d.manage().window().maximize();
                driver.set(d); // Store WebDriver unique to this thread
            }
      
            public static void quitDriver() {
                if (driver.get() != null) {
                    driver.get().quit();
                    driver.remove(); // Remove from ThreadLocal
                }
            }
        }
      
        // com.example.tests.ParallelTest.java
        public class ParallelTest {
            @BeforeMethod
            @Parameters("browser") // Passed from testng.xml
            public void setup(String browser) {
                DriverManager.setDriver(browser); // Set up driver for current thread
                DriverManager.getDriver().get("https://www.example.com");
            }
      
            @Test
            public void verifyTitle() {
                Assert.assertEquals(DriverManager.getDriver().getTitle(), "Example Domain");
            }
      
            @AfterMethod
            public void tearDown() {
                DriverManager.quitDriver(); // Quit driver for current thread
            }
        }
      

      And the testng.xml for parallel execution: XML

        <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
        <suite name="ParallelSuite" parallel="tests" thread-count="2">
            <test name="ChromeTest">
                <parameter name="browser" value="chrome"/>
                <classes>
                    <class name="com.example.tests.ParallelTest"/>
                </classes>
            </test>
            <test name="FirefoxTest">
                <parameter name="browser" value="firefox"/>
                <classes>
                    <class name="com.example.tests.ParallelTest"/>
                </classes>
            </test>
        </suite>
      

9. Reflection (Advanced Framework Capabilities)

  • Java Concept: The ability of a program to examine or modify its own structure and behavior at runtime (e.g., inspect class fields, invoke methods by name).

  • Utilization in Selenium:

    • Selenium PageFactory: This is the most common direct application you'll encounter. PageFactory.initElements() uses Java Reflection to find fields annotated with @FindBy and automatically initialize them as WebElement objects, connecting them to the browser.

    • TestNG's Core: TestNG internally uses reflection to discover all methods annotated with @Test, @BeforeMethod, etc., and then execute them dynamically.

    • Custom Frameworks (Advanced): You might use reflection to dynamically load drivers based on configuration, implement custom test data injection mechanisms, or build very flexible reporting tools.

    • Example (PageFactory is the key user, you rarely write direct reflection for this): Java

        // Inside PageFactory.initElements(driver, pageObject)
        // It iterates through fields of pageObject using reflection:
        // for (Field field : pageObject.getClass().getDeclaredFields()) {
        //     if (field.isAnnotationPresent(FindBy.class)) {
        //         // Use reflection to get @FindBy annotation value
        //         // Create WebElement proxy and set it to the field using field.set(pageObject, proxy)
        //     }
        // }
      

10. External Libraries and Build Tools (Java Ecosystem)

While not part of the core Java language, these are vital Java-based tools and libraries that integrate seamlessly with your Selenium Java framework.

  • 10.1 Build Automation Tools (Maven, Gradle)

    • Java Concept: These are Java-based tools that manage your project's lifecycle, including dependency management, compilation, testing, and packaging.

    • Utilization in Selenium:

      • Dependency Management: Automatically download and manage all required .jar files (Selenium WebDriver, TestNG, Apache POI, logging frameworks, etc.) specified in your pom.xml (Maven) or build.gradle (Gradle).

      • Build & Run: Compile your Java source code, run your TestNG tests, and generate reports.

      • Standardization: Provide a consistent way to build and manage your automation project across different environments.

  • 10.2 Logging Frameworks (Log4j2, SLF4j + Logback)

    • Java Concept: Libraries providing sophisticated logging capabilities beyond System.out.println().

    • Utilization in Selenium: Recording test execution flow, debugging information, errors, and warnings to various outputs (console, file, database). Essential for debugging failed tests and auditing test runs.

  • 10.3 Reporting Libraries (ExtentReports, Allure Report)

    • Java Concept: Java libraries designed to generate visually rich and detailed test reports.

    • Utilization in Selenium: Integrated with TestNG listeners, they capture test results, status, screenshots, and custom logs, providing a comprehensive view of test execution for stakeholders.

More from this blog

Shreenibas Samal's blog

49 posts