Your ultimate guide

Introduction To Software Testing

Software Testing: 
    Software Testing is the process of verifying that a software application meets the specified requirements and works as expected. The main goal of testing is to ensure that the final product is free from defects and performs reliably in real-world conditions.
    By conducting software testing, any bugs or errors in the application can be detected and resolved early in the development cycle, preventing issues before the product is delivered to users.

Importance of Software Testing
A thoroughly tested software product ensures:
  • Reliability - The software performs consistently under different conditions.
  • Security - The system is protected form vulnerabilities and data breaches.
  • High Performance - The application runs smoothly and efficiently.
Overall, software testing helps achieve time savings, cost-effectiveness and greater customer satisfaction.


Manual Testing: 
    In the Manual Testing, we will write some test cases (A document with an expected result -user action and its sub-sequence result) based on the client requirements and execute these test cases manually in the application and verify the actual behaviour of the application we respect to the given expected results.
    
    Manual testers workflow: Requirements -> Analysis -> Test cases -> Execute Test cases against the build deployed by the developer.

Automation Tester:
    Automation testing is done by the tools. Here they going to give all the requirements about the project in script format to that tool. The tool interacts with that application and it will give the output. Automation testing is mainly used for Regression.

- These people get KT from the manual tester (How we execute the test cases on the browser).
- After manual testing is done by the manual tester, then they analyze the test cases.
- Then they start development Scripts.
- Execute these Scripts against the build deployed by the developer

The objective of Automation Testing:
To identify the defects.
- To reduce manual testing activities and redundant test operations using a Systematic solution to achieve better testing coverage. 
- To speed up a software testing process, and to reduce software testing cost & time during a software life cycle. 
- To increase the quality & effectiveness of a software test process by achieving Predefined test criteria in a limited schedule.

When to Use Automation Testing:
- The repetitive tasks are boring or tend to cause human errors.
- Relatively stable areas of the application over volatile ones must be automated. 
- Application with multiple releases / Builds. 
- The application where long & iterative Regression testing cycles are required.
 
When to not use Automation Testing:
- Unstable Application: If the application is frequently changing, automation script may become outdated quickly, leading to high maintenance costs. 
- Tests without Predictable results (Expected results): Automation work best when there are clear expected outcomes. If test results vary unpredictably, manual testing is more suitable. 
- Test cases that require human intervention: Scenarios involving subjective evaluation (e.g., UI/UX, usability, exploratory testing) are better suited for manual testing.




Creating a Simple Maven Project in Eclipse (Step-by-Step Guide)

๐Ÿงฐ Pre-Requisites (What You Need Before Starting)

  1. Java JDK Installed
    • Download and install the latest Java JDK from the official Oracle website.
    • Ensure the `JAVA_HOME` environment variable is set correctly.
  2. Eclipse IDE Installed
    • Install the latest version of Eclipse IDE for Java Developers from official Eclipse website.
  3. Internet Connection
    • You’ll need an active internet connection during the setup to download dependencies and plugins.
  4. TestNG Plugin (Optional, if using TestNG in Maven project)




๐Ÿš€ Steps to Create a Simple Maven Project in Eclipse
1. Open Eclipse IDE
2. Start a New Maven Project
    Go to: File → New → Maven Project
    (If you don’t see "Maven Project", go to `File` → `Other`, then search and select "Maven Project")



3. Project Configuration Window

  • Leave the default settings (location and working set) as-is.
  • Don’t check the “Create a simple project (skip archetype selection)” option.
  • Click Next.


4. Select a Project Template (Archetype)

  • Eclipse will take a few moments to load archetypes (templates).
  • In the "Filter" box, type: `maven-archetype-quickstart`.
  • Select this option from the list and click Next.


5. Enter Project Details
  • Fill in the following fields:
  • Group Id – your project group name (e.g., com.example)
  • Artifact Id – your project name (e.g., my-first-project)
  • Package – base package name (usually same as Group Id)
  • Click Finish.


6. Project Creation in Progress
  • Eclipse will download required files. This may take a minute.
  • In the Console, if it asks “Confirm properties configuration”, just type `Y` and press Enter.

✅ Your Maven project is now created! You’ll see a standard Maven folder structure in your Project Explorer:



Introduction to Apache Maven

๐Ÿงฉ What is Apache Maven?
Apache Maven is a project management and build automation tool for Java applications that is based on POM(Project Object Model). For testers, it’s incredibly helpful for:
  • Managing test libraries and dependencies (like Selenium, TestNG, etc.)
  • Running your test classes automatically
  • Maintaining consistent environments across your team
Even if you don't write application code, Maven is your behind-the-scenes assistant in test automation.




๐Ÿงช Why Should Testers Use Maven?
Here’s how Maven benefits testers:
  1. Easy Dependency Management: Just define required libraries (like Selenium, TestNG) in a file called pom.xml, and Maven downloads them automatically.
  2. Consistent Test Environment: It ensures the same versions of tools/libraries are used across your team or in CI/CD pipelines.
  3. Integrates with Test Frameworks: Works smoothly with popular test tools like JUnit, TestNG, and Cucumber.
  4. Supports Continuous Integration (CI): Easily integrate with tools like Jenkins, GitLab CI, or GitHub Actions for running tests automatically after every code change.
  5. Standard Project Structure: Maven uses a standard directory layout which makes it easier to organize and understand test projects.




๐Ÿš€ Benefits of Using Maven in Eclipse
Here are the key benefits of using Maven (via Eclipse) for testers:
  1. No More JAR Headaches: You don’t have to manually download and add JAR files. Maven downloads them automatically.
  2. Project Setup is Simple: Maven comes with a standard project structure that makes organizing test files easier.
  3. Smooth Integration with Test Frameworks: Maven supports tools like TestNG, JUnit, and Cucumber effortlessly.
  4. Easy to Use in Eclipse: You can create, manage, and run Maven projects within Eclipse without using the command line.


How to Install TestNG in Eclipse (Step-by-Step Guide)

Before you install TestNG in Eclipse, make sure you’ve set up the necessary software and tools. Here’s what you need:




๐Ÿ”ง Pre-Requisites (What You Need First)
  1. Java JDK Installed
    1. Download and install the latest Java JDK.
    2. Make sure the JAVA\_HOME environment variable is set correctly.
  2. Eclipse IDE Installed
    1. Install the latest version of Eclipse IDE for Java Developers from the official Eclipse website.
  3. Internet Connection
    1. An active internet connection is needed during the installation of the TestNG plugin.




๐Ÿš€ How to Install TestNG Plugin in Eclipse

By default, Eclipse does not come with built-in support for TestNG. You’ll need to install it manually using one of the two methods below:

๐Ÿ›’ Method 1: Install via Eclipse Marketplace (Recommended)
1. Open Eclipse IDE
2. Click on the top menu: Help → Eclipse Marketplace...


3. In the search box, type TestNG and press Enter.


4. Click the Install button next to the TestNG plugin.
5. When the confirmation window appears, click Confirm.


6. Accept the license agreement by selecting "I accept the terms..." and click Finish.


7. During installation, if a Trust dialog appears, click Select All → Trust Selected.



8. Once the installation completes, Eclipse may prompt you to restart —go ahead and restart it.

✅ After restart, you’ll be able to create TestNG classes easily in Eclipse.


๐Ÿงฐ Method 2: Install via "Install New Software…" (Manual Method)

1. In Eclipse, go to Help → Install New Software...


2. Click Add...
3. In the dialog box:
    Name: Type anything (e.g., `TestNG`)
    Location: Paste this URL
    ```
    https://testng.org/testng-eclipse-update-site
    ```
   * Then click Add


4. Select the checkbox for TestNG from the list.


5. Click Next, accept all terms and conditions, and then click Finish.
6. Approve any security prompts and complete the installation.
7. Restart Eclipse when prompted.



๐ŸŽ‰ You're Done!

After installation, you can:

* Create new TestNG classes
* Run tests using the TestNG framework
* View results in the TestNG results tab

Getting Started with TestNG – A Beginner-Friendly Guide

What is TestNG?
    TestNG (Test Next Generation) is a powerful open-source testing framework designed for Java. It was developed by Cedric Beust in 2004, inspired by other testing frameworks like JUnit and NUnit.
    TestNG makes writing and running automated tests easier and more flexible. It's especially known for its annotations (like @Test, @BeforeMethod, @AfterClass, etc.) that help control how and when your tests run.
    Another great feature is the DataProvider, which allows you to perform data-driven testing—running the same test with multiple sets of data.




Key Benefits of Using TestNG
Here’s why TestNG is a popular choice among developers and testers:
✅ Powerful Annotations
Easily manage your test setup and teardown using annotations like @BeforeMethod, @AfterMethod, @BeforeClass, and more.

✅ Flexible Test Configuration
You can create test suites, groups, priorities, and dependencies either in a simple XML file or using annotations. This helps you run selected tests and organize them however you need.

✅ Parallel Test Execution
Run multiple tests at the same time to save time—a big advantage when testing large applications.

✅ Detailed Reporting
TestNG automatically generates HTML and XML reports after running tests. You can also integrate with third-party tools like Allure or ExtentReports for advanced visual reports.

✅ Supports All Types of Testing
Whether it’s unit testing, functional testing, integration testing, or end-to-end testing, TestNG can handle it all.




What You Need Before You Start with TestNG
Before diving into TestNG, it helps to have some background knowledge in the following areas:

๐Ÿ“˜ Basic Software Testing Concepts
Understand what test cases are, how testing works, and the types of testing (unit, integration, etc.).

☕ Java Programming Basics
Since TestNG is Java-based, you should know object-oriented programming, exception handling, and how to write simple Java code.

๐Ÿ’ป Familiarity with IDEs
Use an Integrated Development Environment like Eclipse or IntelliJ IDEA, which offer built-in support or easy plugins for TestNG.

Understanding APIs: How Apps Communicate and Work Together

What is an API?
    An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other. APIs define how requests and responses should be formatted so that systems can exchange information seamlessly.

    In simple terms, an API acts like a bridge between two applications. It allows one application to access features or data from another application or service without needing to know how that system is built internally.



Real-World Example: 
    There are several payment gateway services such as PayU, Razorpay, Easebuzz, BillDesk and more.

Let’s take the PayU API as an example.

PayU is a payment gateway service that handles digital transactions. It allows customers to pay using various methods such as:
  • UPI (Unified Payments Interface)
  • Credit Cards
  • Debit Cards
  • Net Banking
  • Wallets (like Paytm, PhonePe, etc.)
When integrating PayU's API into an e-commerce platform:
  1. Developers receive API keys and endpoints URLs.
  2. The API handles:
    • Secure customer payment processing
    • Transaction confirmation
    • Fund transfers to the business account
    • Invoice generation

This entire process is managed through the API without you needing to manually process any payments.



Other Popular APIs

APIs are everywhere and are essential in modern app development. Here are a few more examples:

1. OpenWeatherMap API
  • Used to fetch real-time weather data for any location.
  • You can use it in weather apps, travel apps, or any application needing weather updates.

2. Social Media APIs
  • Allow integration with platforms like Google, Twitter, Facebook, and GitHub.
  • Commonly used for:
    • Social logins (e.g., “Login with Google”)
    • Fetching user profile information
    • Sharing content directly from your app

3. NewsAPI
  • Provides access to news articles from various sources worldwide.
  • Useful for news apps, blogs, or dashboards that display current events.



Why Use APIs?
  • ⚡ Efficiency: Save development time by using existing services.
  • ๐Ÿ”’ Security: APIs provide a secure way to handle sensitive data (like payments).
  • ๐Ÿ“ˆ Scalability: Easily scale or enhance your app by integrating new features via APIs.
  • ๐Ÿงฉ Modularity: Keep your application architecture clean by delegating tasks to external APIs.
Types of APIs
  • Open/Public APIs: Freely available to developers. Often used for public data or services (e.g., weather APIs).
  • Partner APIs: Shared with specific business partners. Controlled access with agreements.
  • Private/Internal APIs: Used within the organization not exposed to external users.
  • Composite APIs: Combine multiple API calls into one. Commonly used in microservices architecture.
APIs Based on Communication Style
     This categorization refers to how data is transmitted between the client (the one making the request) and the server (the one responding). It's about the protocols, formats, and structure used during the commination.

Here are the main types:
  1. Restful (Representational State Transfer)
    • Most popular style of API.
    • Uses HTTP methods like GET, POST, PUT, DELETE.
    • Data is usually sent in JSON or XML format.
    • Stateless: each request is independent.
    • Simple, scalable, and cacheable.
  2. SOAP (Simple Object Access Protocol)
    • A protocol (not just a style) for accessing web services.
    • User XML for request/response formatting.
    • More rigid and verbose, but offers:
      • Built-in security
      • Transactions
      • ACID compliance
    • Suitable for enterprise-level applications.
    • Example: Used in banking, telecom, or any systems needing strict contracts.
  3. GraphQL
    • A query language for APIs created by Facebook.
    • Clients specify exactly what data they need -- nothing more, nothing less.
    • Returns data in a single response, even if it's deeply nested or from multiple resources.
    • Requires a GraphQL server.
    • Example: Instead of calling /users, /posts, and /comments, you send one query to get all related data at once.
  4. gRPC (Google Remote Procedure Call)
    • High-performance RPC framework developed by Google.
    • Uses Protocol Buffers (protobuf) instead of JSON (binary format = faster).
    • Support streaming, authentication, language neutrality.
    • Good for microservices and low-latency systems.
    • Example: Used by internal systems where speed and data compactness matter.
  5. WebSockets
    • Not a traditional API style but used for real-time, two-way communication.
    • Keeps the connection open between client and server.
    • Used in chat apps, gaming, live notifications, etc,
    • Example: A stock trading app updating live prices without refreshing the page.



Final Thoughts:
APIs are a foundational part of modern web and mobile application development. Whether you're building a weather app, a shopping platform, or a news aggregator, APIs allow you to connect your app to powerful external services with minimal effort.

Simple Login Page with Validations

Click on "Forgot Username and Password?" to retrieve your credentials.

Automation Frameworks

Frameworks in Test Automation:
Utilizing a framework facilitates the structured organization of code, providing clear guidelines and best practices to methodically achieve desired outcomes.

Types of Automation Frameworks:
  1. Linear Automation Framework
  2. Modular Driven Framework
  3. Data-Driven Framework
  4. Keyword-Driven Framework
  5. Hybrid Testing Framework
  6. Behavior-Driven Development (BDD) Framework
Let's discuss each of these in detail.




1. Linear Automation Framework
    The Linear Automation Framework, often referred to as the Record & Playback approach, is characterized by its simplicity and ease of implementation. Unlike more complex frameworks, such as Data-Driven or Keyword-Driven frameworks, this approach involves the creation of test scripts within a single class or script file.

How Does It Work?
    Testers record their interactions with the application under test using specialized tools. These interactions are then converted into script commands stored in a single script file. During playback, the recorded actions are executed sequentially, mimicking user interactions.

Advantages:
  • Quick Script Generation – Testers can create scripts quickly by recording their actions without extensive scripting knowledge.
  • Low Barrier to Entry – Beginners can start automating tests with minimal training.
  • Tool Familiarization – Helps testers become familiar with automation tools.

Disadvantages:
  • Limited Reusability – Scripts are linear and cannot be easily reused across multiple tests.
  • Hardcoded Test Data – Test data is embedded within scripts, making updates challenging.
  • Maintenance Challenges – As the test suite grows, maintaining scripts becomes cumbersome.




2. Modular Driven Framework
    The Modular Driven Framework breaks down the application into smaller, independent parts (modules). Each module is tested separately using dedicated scripts, improving reusability and organization.

Advantages:
  • Enhanced Reusability – Test scripts can be reused across different scenarios.
  • Targeted Maintenance – Changes in an application require only specific modules to be updated.
  • Cost-Efficient Maintenance – Clearly separated modules simplify updates and maintenance.
Challenges:
  • Requires Technical Expertise – Knowledge of programming and testing concepts is needed.
  • Time-Consuming Setup – Compared to linear automation, this approach requires careful planning.
  • Hardcoded Test Data – Like the Linear Framework, test data may be embedded in scripts.




3. Data-Driven Testing Framework
    This framework builds upon the Modular Driven Framework by allowing test data to be dynamically supplied from external sources, such as:
  • Excel files
  • CSV files
  • Databases
  • Text files
    Instead of embedding data within scripts, test scripts retrieve data from these external files during execution.

When to Use:
    When testing the same functionality multiple times with different sets of input data.

Advantages:
  • Separation of Test Data and Test Scripts – Updating test data does not affect scripts.
  • Improved Test Coverage – A single test script can be reused with multiple datasets.
  • Flexibility & Maintainability – Test data can be updated independently.
Disadvantages:
  • Increased Complexity – Setting up test data sources requires extra effort.
  • Requires Programming Skills – Testers must understand scripting and data handling.
  • Time-Consuming Setup – Requires significant planning and preparation.




4. Keyword-Driven Testing Framework
    This framework uses keywords stored in an external data file to drive test execution. These keywords represent specific actions to be performed, making the framework structured and reusable.

Advantages:
  • No Programming Skills Required – Testers can create tests using predefined keywords.
  • Simplified Script Creation – Once set up, writing new tests is easier.
  • High Code Reusability – Keywords can be used across multiple scripts.
  • Tool Independence – Works with various test automation tools.
  • Application Independence – Test cases can be designed even before development is complete.
Disadvantages:
  • High Initial Setup Effort – Requires significant time and automation expertise.
  • Higher Initial Investment – More suited for large applications.
  • Complex Maintenance – Managing keywords can become challenging as the framework grows.
  • Longer Learning Curve – Testers must learn how to use and manage keywords effectively.




5. Hybrid Testing Framework
    Hybrid Testing Framework combines features of multiple frameworks, such as Keyword-Driven and Data-Driven approaches, to enhance flexibility and scalability.

Key Components:
  • Driver Script – Controls test execution flow.
  • Configuration File – Stores settings and environment variables.
  • Run Manager – Determines which tests to run.
  • Test Cases & Scripts – Defines automation scenarios.
  • Object Repository – Stores UI elements for easy identification.
  • Test Data – Externalized data sources (Excel, CSV, Databases).
  • Results & Logs – Stores test execution reports.
  • Function Library – Collection of reusable functions.
  • Scheduler – Automates test execution at predefined intervals.
Advantages:
  • Best of Multiple Frameworks – Combines strengths of Keyword-Driven and Data-Driven frameworks.
  • High Flexibility & Reusability – Adaptable to different testing needs.
  • Faster Execution – Optimized test execution time.
  • Scalability – Supports multi-platform and cross-browser testing.
Disadvantages:
  • Requires Strong Technical Expertise – Developers must understand multiple frameworks.
  • Higher Initial Effort – Requires significant setup time and investment.




6. Behavior-Driven Development (BDD) Framework
    BDD enables teams to create test cases in plain, human-readable language (e.g., English). This improves collaboration between testers, developers, and business analysts.

Given-When-Then Approach:
BDD follows a structured format:
  • Given – Defines initial conditions.
  • When – Describes user actions.
  • Then – Specifies expected outcomes.
Example Feature File (Cucumber - Gherkin Format): gherkin

Feature: BDD implementation using Cucumber  
Scenario: Login to Gmail using Cucumber plugin  
  Given User is navigating to the Gmail login page  
  When User enters username as "Username" and password as "Password"  
  Then User is successfully navigated to the Gmail mailbox

Advantages:
  • Improved Test Coverage – Ensures all user stories are tested.
  • Readable Scenarios – Uses natural language for easy understanding.
  • Test Automation Friendly – Works with Cucumber, SpecFlow, and JBehave.
  • Code Reusability – Steps can be reused across test cases.
  • CI/CD Integration – Easily fits into Continuous Integration pipelines.

Disadvantages:
  • Requires Collaboration – Close coordination between developers and testers is needed.
  • Risk of Misuse – If not used correctly, BDD can turn into an inefficient testing approach.

Conclusion:
Selecting the right automation framework depends on project requirements, team expertise, and long-term maintainability. Linear and Modular frameworks are best for small projects, while Data-Driven, Keyword-Driven, Hybrid, and BDD frameworks are ideal for large-scale automation efforts.

File Upload Demo Page



Waits Demo Page

Delayed Actions

Drag and Drop Demo Page

Drag and Drop Demo

๐Ÿ‘‰ How to Use: Click and hold on any element to drag it. Then drop it anywhere inside the box to rearrange or duplicate it. Have fun organizing!

Element 1
Element 2
Element 3






















File Upload Using Selenium WebDriver

Exploring Different Approaches for File Upload with Selenium WebDriver:

........Incomplete.......
    File uploads are a common functionality on web applications, and automating this process is crucial for efficient testing with Selenium WebDriver. In this blog post, we will explore three different methods to upload files using Selenium WebDriver: 'SendKeys', the 'Robot' class, and 'AutoIT'.

Using SendKeys:
    The most straightforward approach for uploading a file in Selenium WebDriver is to use the 'SendKeys' method. This method is applicable only if the HTML input element has the attribute type="file". This attribute is specific to file upload functionality, and using Selenium's sendKeys method allows for the automatic selection of the desired file for this type of input field.
Syntax:
  1. WebElement fileInput = driver.findElement(By.id("idvlaue"));
  2. fileInput.sendKeys("path/to/your/file.txt");
Pros:
  • Directly interacts with the file input element.
  • Simple and concise code for file uploads.
  • No external dependencies are required.
Cons:
  • Limited to scenarios where the file input element is present.

Using Robot Class:
    The Robot class in Java can be used to simulate keyboard and mouse actions. In the context of the uploads, the Robot class can be used to navigate the file selection dialogue.

Example Program:
  1. import java.awt.AWTException;
  2. import java.awt.Robot;
  3. import java.awt.Toolkit;
  4. import java.awt.datatransfer.StringSelection;
  5. import java.awt.event.KeyEvent;
  6.  
  7. import org.openqa.selenium.By;
  8. import org.openqa.selenium.WebDriver;
  9. import org.openqa.selenium.WebElement;
  10. import org.openqa.selenium.chrome.ChromeDriver;
  11. import org.openqa.selenium.chrome.ChromeOptions;
  12.  
  13. public class Dummy2 {
  14. public static void main(String[] args) throws AWTException {
  15. ChromeOptions co = new ChromeOptions();
  16. co.addArguments("-remote-allow-origins");
  17.  
  18. WebDriver driver = new ChromeDriver();
  19.                 driver.get("https://testingcolleges.blogspot.com/2024/01/file-upload-demo-page.html");
  20.  
  21. WebElement fileUploadBtn = driver.findElement(By.className("file-label-2"));
  22. fileUploadBtn.click();
  23.  
  24. Robot rbt = new Robot();
  25. rbt.delay(2000); // just like thread.sleep
  26.  
  27. //these below 2 lines used to copy the path 
  28. StringSelection ss = new StringSelection("C:\\Users\\Dollar\\Desktop\\Dummy.txt");
  29. // copy the above path in clipboard
  30. Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
  31. //Toolkit.getDefaultToolkit().getSystemClipboard().setContents("path", null);
  32.  
  33. //perform Ctrl+V operation to pass the copied path
  34. rbt.keyPress(KeyEvent.VK_CONTROL);
  35. rbt.keyPress(KeyEvent.VK_V);
  36. rbt.keyRelease(KeyEvent.VK_CONTROL);
  37. rbt.keyRelease(KeyEvent.VK_V);
  38.  
  39. //Enter press
  40. rbt.keyPress(KeyEvent.VK_ENTER);
  41. rbt.keyRelease(KeyEvent.VK_ENTER);
  42.  
  43. }
  44. }

Pros:
  • Works across different browsers.
  • Can handle scenarios with hidden file input fields.
Cons:
  • Requires handling keyboard events, which may be error-prone.
  • Platform-dependent and may need adjustments for different operating systems.
Using AutoIT:
    AutoIT is a scripting language designed for automating the Windows GUI and general scripting tasks. It can be integrated with Selenium WebDriver to handle file Uploads.
Pros:
  • Powerful for handling complex file upload scenarios.
  • Works seamlessly across different browsers and operating systems.
Cons:
  • Requires installing AutoIT and writing an external script.
  • Add an external dependency to your automation project.


Conclusion:
    Each method for file upload with Selenium WebDriver has its advantages and limitations. The choice of method depends on the specific requirements of your application and the level of control and compatibility needed. While SendKeys is suitable for simple scenarios, the Robot class and AutoIT offer more flexibility and control, making them valuable tools for handling complex file upload functionalities.




Browser Window Sizes and Positions


maximize(): The maximize() method is used to maximize the browser window. This is often done to ensure that the web page is displayed in its full size on the screen. Here's an example of how you can use the 'maximize' method in selenium with Java:

  1. public class Maximize {
  2.     public static void main(String[] args) {
  3.         WebDriver driver = new ChromeDriver();
  4.         driver.manage().window().maximize();
  5.     }
  6. }

How to Minimize the Browser Window in Selenium?
    Selenium's Java has no built-in method to minimize the browser window. However, Selenium's Python does have a minimize function.




getSize(): The getSize() method is used to get the height and width of a WebElement/BrowserWindow. The getSize() method returns an object of type 'Dimension', and you can use its 'getHeight' and 'getWidth' methods to obtain the height and width, respectively.

Example 1: To get the height and width of a web element.
  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.Dimension;
  3. import org.openqa.selenium.WebDriver;
  4. import org.openqa.selenium.WebElement;
  5. import org.openqa.selenium.chrome.ChromeDriver;
  6. public class GetElementSize {
  7.     public static void main(String[] args) {
  8.         WebDriver driver = new ChromeDriver();
  9.         driver.get("https://example.com");
  10.         WebElement element = driver.findElement(By.id("value"));
  11.         Dimension size = element.getSize();
  12.         System.out.println("Height: " + size.getHeight());
  13.         System.out.println("Width: " + size.getWidth());
  14.     }
  15. }
Example 2: To get the height and width of a Browser Window.
  1. import org.openqa.selenium.Dimension;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.chrome.ChromeDriver;
  4. public class GetBrowserWindowSize {
  5.     public static void main(String[] args) {
  6.         WebDriver driver = new ChromeDriver();
  7.         driver.get("https://example.com");
  8.         Dimension windowSize = driver.manage().window().getSize();
  9.         System.out.println("Window Height: " + windowSize.getHeight());
  10.         System.out.println("Window Width: " + windowSize.getWidth());
  11.     }
  12. }
Note: In the above example instead of creating the Dimension class object we can also directly give the methods:
driver.manage().window().getSize().getHeight();
driver.manage().window().getSize().getWidth();




Resize the Browser window:
    To resize the Browser window. 'manage().window().setSize()' is a predefined method of the Selenium 'WebDriver' class.
Syntax 1:
  1. Dimension newSize = new Dimension(800, 600); //(width, height)
  2. driver.manage().window().setSize(newSize);

Syntax 2:
  1. driver.manage().window.setSize(new Dimension(800, 600));

Example:
  1. import org.openqa.selenium.Dimension;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.chrome.ChromeDriver;
  4. public class ResizeWindow {
  5.     public static void main(String[] args) {
  6.         System.setProperty("webdriver.chrome.driver", "path/chromedriver.exe");
  7.         WebDriver driver = new ChromeDriver();
  8.         driver.get("http://example.com/");
  9.         Dimension newSize = new Dimension(800, 600);
  10.         driver.manage().window().setSize(newSize);
  11.     }
  12. }
Note: In Eclipse, you may have recommend two import statements for the 'Dimension' class: 'import java.awt.Dimension;' and 'import org.openqa.selenium.Dimension;'. You should only select 'import org.openqa.selenium.Dimension;'. 




getPosition():
    getPosition() method gets the position of the current window, relative to the upper left corner of the screen. The method takes no arguments and returns a Point object, which contains the X and Y coordinates of the window.

Syntax:(With Point object)
  1. // Get the position of the current window
  2. Point p = driver.manage().window().getPosition();
  3. // Print the X and Y coordinates of the window
  4. System.out.println("X Coordinate: " + p.getX());
  5. System.out.println("Y Coordinate: " + p.getY());
Syntax: (We can also print the X and Y Coordinates without creating a Point object)
  1. System.out.println("X Coordinate: "driver.manage().window().getPosition().getX());
  2. System.out.println("Y Coordinate: " + driver.manage().window().getPosition().getY());

Example:
  1. import org.openqa.selenium.WebDriver;
  2. import org.openqa.selenium.chrome.ChromeDriver;
  3. public class WindowPosition {
  4.     public static void main(String[] args) {
  5.         System.setProperty("webdriver.chrome.driver", "path/chromedriver.exe");
  6.         WebDriver driver = new ChromeDriver();
  7.         driver.get("http://testingcolleges.blogspot.com/");
  8.         System.out.println("X Coordinate: " + driver.manage().window().getPosition().getX());
  9.         System.out.println("Y Coordinate: " + driver.manage().window().getPosition().getY());
  10.     }
  11. }
Output:
X Coordinate: 10
Y Coordinate: 10




setPosition():
    The setPosition() method in Selenium Webdriver sets the position of the current window relative to the top left corner of the screen. The Point class instance specifies the target position of the window.

Syntax 1:
  1. Point p = new Point(250, 250);
  2. driver.manage().window().setPosition(p);
Syntax 2:
  1. driver.manage().window().setPosition(new Point(250, 250));

Example:
  1. import org.openqa.selenium.WebDriver;
  2. import org.openqa.selenium.chrome.ChromeDriver;
  3. import org.openqa.selenium.Point;
  4. public class Position {
  5.     public static void main(String[] args) {
  6.         System.setProperty("webdriver.chrome.driver", "path/chromedriver.exe");
  7.         WebDriver driver = new ChromeDriver();
  8.         driver.get("http://testingcolleges.blogspot.com/");
  9.         Point p = new Point(250,250);
  10.         driver.manage().window().setPosition(p);
  11.     }
  12. }




****