0% found this document useful (0 votes)
3 views

encapsulation_java

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

encapsulation_java

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Encapsulation in Java for Selenium

Projects: A Comprehensive
Beginner's Guide
When learning Java Selenium, understanding object-oriented programming concepts is
essential. Encapsulation is one of these foundational concepts. In this post, we’ll explore
encapsulation in depth, how it is applied in Java Selenium, and its role in building robust
automation frameworks. By the end, you’ll also see an example of a real-world Selenium
framework demonstrating encapsulation in action.

What is Encapsulation?

Encapsulation is the process of wrapping data (variables) and methods (functions) into a
single unit, typically a class. In simpler terms, it’s about controlling access to the inner
workings of a class while exposing only what is necessary.

This is achieved through:

1. Private access modifiers to restrict direct access to class variables.


2. Public getter and setter methods to control how these variables are accessed and
modified.

Encapsulation helps:

● Protect data from unauthorized access.


● Enhance maintainability by allowing changes to internal implementation without
affecting external code.
● Promote modular and reusable code.

Examples to Understand Encapsulation:

● Safe Deposit Locker: Imagine you have a safe deposit locker at a bank. Only you (or
someone you authorize) can access it using a key. The locker is like a class, the
contents are private data, and the key is a method to access it.
● Car Controls: You use a steering wheel, accelerator, and brakes (public methods) to
control the car, without needing to know how the engine or transmission works
(private implementation).
Encapsulation in Java Selenium

In Selenium automation, encapsulation is crucial for maintaining clean and maintainable


test code. It helps abstract web element interactions, test data, and configuration details,
ensuring that the test scripts remain independent of implementation details.

Basic Example

Let’s start with a simple example: managing user login details.

// Class to encapsulate user details


public class User {
private String username;
private String password;

// Constructor
public User(String username, String password) {
this.username = username;
this.password = password;
}

// Getters
public String getUsername() {
return username;
}

public String getPassword() {


return password;
}

// Setters (optional, if values need to change)


public void setUsername(String username) {
this.username = username;
}

public void setPassword(String password) {


this.password = password;
}
}
Step-by-Step Code Execution:

1. Private Variables:

○ The username and password variables are declared as private to ensure that
they are not accessible directly from outside the class.
○ This enforces encapsulation, as external classes cannot modify these
variables directly.
2. Constructor Initialization:

○ The constructor public User(String username, String password) initializes


the username and password fields when an instance of the User class is
created.
○ This ensures that each User object starts with a specific set of data,
enforcing a controlled way to initialize objects.
3. Getter Methods:

○ Public getter methods (getUsername() and getPassword()) allow controlled


access to the private variables.
○ These methods ensure that other classes can read the values, but cannot
modify them directly. This approach makes sure that data is accessed in a
controlled manner.
4. Setter Methods:

○ Public setter methods (setUsername() and setPassword()) allow other


classes to modify the private variables.
○ By using setters, we can control how and when the variables are updated,
ensuring that values are set according to specific rules or constraints.
5. Usage in Selenium Script:

○ When creating a User object, we can use the getUsername() and


getPassword() methods to retrieve the username and password for login in
the Selenium script.
○ This ensures that the sensitive data is protected and can only be accessed in
a controlled way.

Encapsulation in a Selenium Page Object Model

Now, let’s see how encapsulation is applied in the Page Object Model (POM), a common
design pattern in Selenium.
// Encapsulation in a Login Page
public class LoginPage {
private WebDriver driver;

private By usernameField = By.id("username");


private By passwordField = By.id("password");
private By loginButton = By.id("loginButton");

public LoginPage(WebDriver driver) {


this.driver = driver;
}

public void enterUsername(String username) {


driver.findElement(usernameField).sendKeys(username);
}

public void enterPassword(String password) {


driver.findElement(passwordField).sendKeys(password);
}

public void clickLogin() {


driver.findElement(loginButton).click();
}
}

Step-by-Step Code Execution:

1. Private Locators:

○ The usernameField, passwordField, and loginButton locators are declared as


private variables.
○ This ensures that these locators cannot be directly accessed or modified
from outside the LoginPage class.
○ By encapsulating these details, we provide controlled access through public
methods, which helps maintain code security and flexibility.
2. Constructor Injection:

○ The constructor public LoginPage(WebDriver driver) takes a WebDriver


instance as an argument and initializes the LoginPage object.
○ This way, the WebDriver is injected into the LoginPage, allowing the class to
interact with the web page without hardcoding dependencies.
3. Public Methods:

○ Methods like enterUsername(), enterPassword(), and clickLogin() are public


and provide controlled access to perform actions on the login page.
○ These methods encapsulate the internal implementation of interacting with
the page and expose only the necessary actions, allowing external code to
interact with the page without knowing the internal details of the page
structure.

Real-World Framework Example

Let’s create a sample framework for an e-commerce website. The framework will:

1. Encapsulate web elements in Page Objects.


2. Encapsulate configurations in a ConfigurationManager.
3. Use encapsulation to manage test workflows.

Step 1: ConfigurationManager
public class ConfigurationManager {
private static final String BASE_URL = "https://ecommerce.com";
private static final String BROWSER = "chrome";

public static String getBaseUrl() {


return BASE_URL;
}

public static String getBrowser() {


return BROWSER;
}
}

Step-by-Step Code Execution for ConfigurationManager:

1. Private Variables:

○ The BASE_URL and BROWSER variables are declared as private static final,
meaning their values cannot be changed once set.
○ These variables are encapsulated within the ConfigurationManager class to
provide controlled access.
2. Public Getters:

○ The public methods getBaseUrl() and getBrowser() are provided to allow


other parts of the code to access these values.
○ These methods return the private variables, ensuring that the external code
can retrieve these configurations in a controlled manner.
○ By keeping the configuration values private, we ensure that they are not
inadvertently modified by external classes.
3. Usage:

○ Other test scripts can access configuration details (like the base URL or
browser type) via the ConfigurationManager.getBaseUrl() and
ConfigurationManager.getBrowser() methods, ensuring encapsulation
principles are maintained.

Step 2: Page Objects


public class HomePage {
private WebDriver driver;

private By searchBox = By.id("search");


private By searchButton = By.id("search-button");

public HomePage(WebDriver driver) {


this.driver = driver;
}

public void searchForItem(String item) {


driver.findElement(searchBox).sendKeys(item);
driver.findElement(searchButton).click();
}
}
Step-by-Step Code Execution for HomePage:

1. Private Locators:

○ The searchBox and searchButton locators are declared as private to prevent


external classes from accessing or modifying them directly.
○ This encapsulation ensures that any changes to the locators (like a change
in the ID attribute) are contained within the HomePage class and do not
affect other parts of the test.
2. Constructor Injection:

○ The constructor public HomePage(WebDriver driver) accepts a WebDriver


instance, which is used to interact with the browser.
○ By passing the WebDriver instance into the HomePage, we enable the class
to perform actions on the page, maintaining flexibility and testability.
3. Public Method:

○ The searchForItem() method is a public method that encapsulates the


action of searching for an item on the homepage.
○ By exposing this method, we allow the test scripts to search for items
without knowing the internal details of how the search functionality works
on the webpage.

Step 3: Test Workflow


public class SearchTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get(ConfigurationManager.getBaseUrl());

HomePage homePage = new HomePage(driver);


homePage.searchForItem("Laptop");

driver.quit();
}
}
Step-by-Step Code Execution for SearchTest:

1. Driver Initialization:

○ A WebDriver instance (ChromeDriver) is created to launch the browser.


○ The browser is initialized by calling new ChromeDriver(), ensuring that we
are using the correct browser type as per the configuration.
2. Base URL:

○ The ConfigurationManager.getBaseUrl() method is called to retrieve the


base URL for the e-commerce website.
○ This encapsulates the URL configuration, allowing us to change the base
URL in one central location without modifying the test scripts.
3. Page Object Interaction:

○ An instance of HomePage is created, and the searchForItem() method is


called to perform the search action on the page.
○ This demonstrates how encapsulation helps maintain clean, reusable, and
independent test scripts.
4. Cleanup:

○ The browser is closed using driver.quit(), ensuring that the test session is
properly cleaned up.

This detailed guide provides an in-depth understanding of encapsulation in Java


Selenium, with step-by-step explanations of each code example. Feel free to reach out if
you have more questions!

You might also like