Showing posts with label Web Testing. Show all posts
Showing posts with label Web Testing. Show all posts

January 29, 2026

High-Impact Java Strategies to Build Scalable Test Automation Frameworks

SDETs and QA: Learn with the runnable Core Java Playbook for Interview Preparation Practice. View the Core Java playbook in action in the video below.

Summary: Many test automation frameworks fail not because of tools, but because of weak Java design decisions. This post explains high-impact Java strategies that help you build scalable, stable, and professional test automation frameworks.

Introduction: The SDET’s Hidden Hurdle

Moving from manual testing to automation is a big career milestone. Writing scripts that click buttons and validate text feels good at first.

Then reality hits. As the test suite grows, maintenance effort explodes. Tests become fragile, execution slows down, and engineers spend more time fixing automation than testing the application.

This problem is often called automation rot. It happens when automation is treated as scripting instead of engineering.

The solution is not a new tool. It is mastering Java as an engineering language for automation. By applying proven Java design and concurrency strategies, you can turn brittle scripts into a scalable, industrial-grade framework.

1. Why Singleton and Factory Patterns Are Non-Negotiable

In professional frameworks, WebDriver management determines stability. Creating drivers inside individual tests is a fast path to flaky behavior and resource conflicts.

The Singleton pattern ensures that only one driver instance exists per execution context. It acts as a guardrail, preventing accidental multiple browser launches.

The Factory pattern centralizes browser creation logic. Instead of hard-coding Chrome or Firefox inside tests, the framework decides which browser to launch at runtime.


// Singleton: ensure a single driver instance
public static WebDriver getDriver() {
    if (driver == null) {
        driver = new ChromeDriver();
    }
    return driver;
}

// Factory: centralize browser creation
public static WebDriver getDriver(String browser) {
    switch (browser.toLowerCase()) {
        case "chrome": return new ChromeDriver();
        case "firefox": return new FirefoxDriver();
        default: throw new IllegalArgumentException("Unsupported browser");
    }
}
  

Centralizing browser creation gives you one place to manage updates, configuration, and scaling as the framework grows.

2. The Finally Block Is Your Best Defense Against Resource Leaks

Exception handling is not just about catching failures. It is about protecting your execution environment.

The finally block always executes, whether a test passes or fails. This makes it the correct place to clean up critical resources such as browser sessions.


try {
    WebElement button = driver.findElement(By.id("submit"));
    button.click();
} catch (NoSuchElementException e) {
    System.out.println("Element not found: " + e.getMessage());
} finally {
    driver.quit();
}
  

Without proper cleanup, failed tests leave behind ghost browser processes. Over time, these processes consume memory and crash CI runners.

Using finally consistently keeps both local machines and CI pipelines stable.

3. Speed Up Feedback with Multi-Threading and Parallel Execution

Sequential execution is one of the biggest bottlenecks in modern automation. Long feedback cycles slow teams down and reduce confidence.

Java provides powerful concurrency tools that allow tests to run in parallel. Instead of managing threads manually, professional frameworks use ExecutorService to control a pool of threads.

This approach allows multiple test flows or user simulations to run at the same time, cutting execution time dramatically.

Engineers who understand thread safety, shared resources, and controlled parallelism are the ones who design frameworks that scale.

4. Decouple Test Data with the Strategy Pattern

Hard-coding test data tightly couples your tests to a specific source. This makes frameworks rigid and difficult to extend.

The Strategy pattern solves this by defining a contract for data access and allowing implementations to change at runtime.


// Strategy interface
public interface DataStrategy {
    List<String> getData();
}

// Runtime selection
DataStrategy strategy = new CSVDataStrategy();
List<String> testData = strategy.getData();
  

With this approach, switching from CSV to JSON or a database requires no changes to test logic. The test focuses on validation, not data plumbing.

5. Stabilize Tests by Mocking Dependencies with Mockito

Automation should fail only when the application is broken. External systems such as databases or third-party services introduce noise and false failures.

Mockito allows you to isolate the unit under test by mocking dependencies and controlling their behavior.


// Mock dependency
Service mockService = Mockito.mock(Service.class);

// Stub behavior
when(mockService.getData()).thenReturn("Mock Data");
  

Mocking removes instability and keeps tests focused on the logic being validated. This dramatically increases trust in automation results.

Conclusion: From Tester to Automation Engineer

Strong automation frameworks are built, not scripted.

By applying Java design patterns, proper resource management, parallel execution, data decoupling, and mocking, you move from writing tests that merely run to engineering systems that scale.

These skills separate automation engineers from automation scripters.

Final thought: is your current framework just running tests, or is it engineered to grow with your product?

If you want any of the following, send a message using the Contact Us (right pane) or message Inder P Singh (19 years' experience in Test Automation and QA) in LinkedIn at https://www.linkedin.com/in/inderpsingh/

  • Production-grade Java for Test Automation automation templates with playbooks
  • Working Java for Test Automation projects for your portfolio
  • Deep-dive hands-on Java for Test Automation training
  • Java for Test Automation resume updates

January 06, 2026

XPath Techniques To Make Your Automation Tests Unbreakable

Summary: Fragile XPath locators are one of the biggest causes of flaky automation tests. This article shares five proven XPath techniques that help you write stable, readable, and long-lasting locators that can survive UI changes. First, view the XPath tutorial for beginners below. Then, read on.

Introduction

If you work in test automation, you know the frustration well. Tests fail not because the application is broken, but because a small UI change invalidated your locators.

This problem wastes time, increases maintenance effort, and erodes trust in automation. The good news is that most of these failures are avoidable.

Stop thinking of XPath as just a way to locate elements and start treating it as a language for describing elements in a stable and logical way.

Try the free XPath Playbook on GitHub with demo XPaths.

In this post, we will look at five XPath techniques that can turn brittle locators into robust, maintainable ones.

1. Avoid Absolute Paths and Prefer Relative XPath

The first step toward reliable locators is understanding the difference between absolute and relative XPath.

An absolute XPath starts from the root of the document and defines every step along the way. While this may look precise, it is extremely fragile. A single extra container added to the page can break the entire path.

Relative XPath, on the other hand, focuses on the unique characteristics of the target element and ignores irrelevant structural details.

For example, instead of relying on a full path from the root, describe the element based on a stable attribute or relationship. Relative XPath continues to work even when the surrounding structure changes.

Avoid: //html/body/div[2]/div[1]/form/input[2]
Prefer: //form//input[@name='email']

As a rule, absolute XPath has no place in a professional automation framework.

Note: Want to learn XPath in detail? View How to find XPath tutorial.

2. Use XPath Axes to Navigate Smartly

Many testers think XPath only works top to bottom through the DOM. This limited understanding leads to weak locators.

XPath axes allow you to navigate in all directions: up, down, and sideways. This lets you describe an element based on its relationship to another stable element.

Some commonly used axes include ancestor, parent, following-sibling, and preceding-sibling.

This approach is especially powerful when the element you want does not have reliable attributes. Instead of targeting it directly, you anchor your XPath to nearby text or labels that rarely change.

For example, rather than locating an input field directly, you can describe it as the input that follows a specific label. This makes the locator far more resilient.

//label[normalize-space()='Password']/following-sibling::input[1]
//div[contains(@class,'card')]/ancestor::section[1]

3. Handle Messy Text with normalize-space()

Text-based locators often fail because of hidden whitespace. Extra spaces, line breaks, or formatting changes can cause simple text checks to stop working.

The normalize-space() function solves this problem by trimming leading and trailing spaces and collapsing multiple spaces into one.

//button[normalize-space()='Submit']
//h3[normalize-space()='Account Settings']

When you use normalize-space(), your locator becomes immune to minor formatting differences in the UI. This single function can eliminate a surprising number of flaky failures.

If you are locating elements by visible text, normalize-space() should be your default choice.

Brittle XPath Locators vs Robust XPath Locators

4. Defeat Dynamic Attributes with Partial Matching

Modern web applications often generate dynamic values for attributes like id and class. Trying to match these values exactly is a common mistake.

XPath provides functions like contains() and starts-with() that allow you to match only the stable portion of an attribute.

Use starts-with() when the predictable part appears at the beginning of the value, and contains() when it can appear anywhere.

//input[starts-with(@id,'user_')]
//div[contains(@class,'item-') and contains(@class,'active')]

This technique is essential for dealing with dynamic IDs, timestamps, and auto-generated class names. It dramatically reduces locator breakage when the UI changes slightly.

5. Combine Conditions for Precise Targeting

Sometimes no single attribute is unique enough to identify an element reliably. In such cases, combining multiple conditions is the best approach.

XPath allows you to use logical operators like and and or to build precise locators. This is similar to using a composite key in a database.

By combining class names, text, and attributes, you can describe exactly the element you want without relying on fragile assumptions.

//a[@role='button' and contains(@href,'/checkout') and normalize-space()='Buy now']

This strategy ensures that your locator is specific without being overly dependent on one fragile attribute.

Conclusion: Write Locators That Survive Change

Stable XPath locators are not about clever tricks. They are about clear thinking and disciplined design.

When you start describing elements based on stable characteristics and relationships, your automation becomes more reliable and easier to maintain.

Adopt a locator-first mindset. Write XPath expressions that anticipate change instead of reacting to it. That mindset is what separates brittle test suites from professional automation.

To get working Selenium/Cypress/Playwright projects for your portfolio (paid service), deep-dive in-person Test Automation and QA Training and XPath resume updates, send me a message using the Contact Us (right pane) or message Inder P Singh (18 years' experience in Test Automation and QA) in LinkedIn at https://www.linkedin.com/in/inderpsingh/

January 05, 2026

5 Powerful TestNG Features That Will Transform Your Automation Framework

Summary: Many teams use TestNG only for basic test annotations, but the framework offers more. This article explores five powerful TestNG features that help you build resilient, scalable, and professional test automation frameworks. View TestNG Interview Questions and Answers here.

Introduction

For many developers and SDETs, TestNG starts and ends with the @Test annotation. It is often used simply to mark methods as test cases and run them in sequence.

But using only @Test means you are missing most of what makes TestNG such a powerful test framework. TestNG was designed to solve real-world automation problems like flaky tests, complex execution flows, reporting, and parallel execution.

In this post, we will explore TestNG features that can move you from writing basic tests to designing a robust automation architecture. First, view my TestNG Tutorial for beginners below. Then, read on.


1. Stop at the End, Not the First Failure with SoftAssert

By default, TestNG assertions are hard assertions. As soon as one assertion fails, the test method stops executing. This behavior is efficient, but it can be frustrating when validating multiple conditions on the same page.

SoftAssert solves this problem by allowing the test to continue execution even after an assertion failure. Instead of stopping immediately, all failures are collected and reported together at the end of the test.

You create a SoftAssert object, perform all your checks, and then call assertAll() once. If you forget that final step (which is a common mistake), the test will pass even when validations fail.

SoftAssert is especially useful for UI testing, where validating all elements in a single run saves time and reduces repeated test executions.

2. Reduce Noise from Flaky Tests with RetryAnalyzer

Every automation engineer has dealt with flaky tests. These tests fail intermittently due to temporary issues like network delays, browser instability, or backend hiccups.

TestNG provides a built-in solution through RetryAnalyzer. This feature allows you to automatically retry a failed test a specified number of times before marking it as failed.

You implement the IRetryAnalyzer interface and define retry logic based on a counter. Once configured, a test can be retried automatically without any manual intervention.

RetryAnalyzer should be used carefully. It is meant to handle transient failures, not to hide real defects. When used correctly, it can significantly stabilize CI pipelines.

3. Build Logical Test Flows with Groups and Dependencies

TestNG allows you to control execution flow without writing complex conditional logic. Two features make this possible: groups and dependencies.

Groups allow you to categorize tests using meaningful labels like smoke, sanity, or regression. You can then selectively run specific groups using your test configuration.

Dependencies let you define relationships between tests. A test can be configured to run only if another test or group passes successfully. If the dependency fails, the dependent test is skipped automatically.

This approach is ideal for modeling workflows such as login before checkout or setup before validation. Just be careful not to create long dependency chains, as one failure can skip many tests.

To get working TestNG projects for your portfolio (paid service) and TestNG resume updates, send a message using the Contact Us (right pane) or message Inder P Singh in LinkedIn at https://www.linkedin.com/in/inderpsingh/

4. Speed Up Execution with Parallel DataProviders

Data-driven testing is one of TestNG’s most popular features, thanks to the @DataProvider annotation. It allows the same test to run multiple times with different input data.

What many teams miss is that DataProviders can run in parallel. By enabling parallel execution, each dataset can be processed simultaneously across multiple threads.

This feature is very useful for large datasets, API testing, and scenarios where execution time is critical. When combined with a well-designed thread-safe framework, it can reduce overall test duration.

Parallel execution requires careful resource management. Shared objects and static variables must be handled correctly to avoid race conditions.

5. Extend the Framework with TestNG Listeners

Listeners are one of TestNG’s most powerful features. They allow you to hook into test execution events and run custom logic when those events occur.

Using listeners, you can perform actions such as taking screenshots on failure, logging detailed execution data, integrating with reporting tools, or sending notifications.

For example, the ITestListener interface lets you execute code when a test starts, passes, fails, or is skipped. This makes listeners ideal for cross-cutting concerns that should not live inside test methods.

Listeners become even more powerful when combined with features like RetryAnalyzer, enabling advanced behaviors such as alerting only after all retries fail.

Conclusion

TestNG is far more than a basic testing framework. Its strength lies in features that give you control over execution, resilience against failures, and scalability for large test suites.

By using SoftAssert, RetryAnalyzer, groups and dependencies, parallel DataProviders, and listeners, you can build automation frameworks that are cleaner, faster, and more reliable.

Now take a look at your current TestNG suite. Which of these features could you apply to remove your biggest testing bottleneck?

If you want deep-dive in-person Test Automation and QA projects-based TestNG Training, send a message using the Contact Us (right pane) or message Inder P Singh (18 years' experience in Test Automation and QA) in LinkedIn at https://www.linkedin.com/in/inderpsingh/

December 30, 2025

Powerful Cypress Features You Are Probably Underusing in Web Testing

Summary: Cypress is more than just an end-to-end testing tool. Its unique architecture, automatic waiting, and network control solve many long-standing problems in test automation. In this blog post, we explore key Cypress features that SDETs and QA Engineers often underuse. I explain how they can dramatically improve test reliability, speed, and developer confidence.
Note: You can view Cypress Interview Questions and Answers short video here.

Introduction

If you have worked on any complex web application, you know the pain points of test automation. Flaky tests that fail without a clear reason, complex setup steps that take hours, and slow feedback loops that frustrate developers.

For years, these issues were accepted as the cost of doing automated testing. Cypress challenges that mindset. It was built from the ground up to eliminate these problems rather than work around them. First view my Cypress Test Automation video below. Then read on.

Cypress is not just another Selenium-style tool. Its design unlocks capabilities that often feel surprising when you first experience them. Below are four Cypress features that can turn testing from a bottleneck into a real productivity booster.

Feature 1: Cypress Runs Inside the Browser

The most important difference between Cypress and traditional tools is its architecture. Cypress runs directly inside the browser, sharing the same event loop as your application.

Behind the scenes, Cypress uses a two-part system. A Node.js process runs in the background to handle tasks like screenshots, videos, and file access. At the same time, your test code executes inside the browser with direct access to the DOM, application code, window object, and network traffic.

This is very different from tools that rely on WebDriver and external processes. By removing that middle layer, Cypress delivers faster execution, more consistent behavior, and far fewer random failures.

Because Cypress lives where your application lives, it can observe and control behavior with a level of reliability that traditional tools struggle to achieve.

Feature 2: Automatic Waiting Removes Timing Headaches

Timing issues are one of the biggest causes of flaky tests. Many SDETs or QA Engineers rely on hard-coded delays or complex async logic just to wait for elements or API responses.

Cypress eliminates this problem with built-in automatic waiting. Every Cypress command is queued and executed in order. Cypress automatically waits for elements to appear, become visible, and be ready for interaction before moving on.

Assertions also retry automatically until they pass or reach a timeout. This means you do not need explicit waits, sleeps, or manual retries. The result is cleaner, more readable tests that focus on intent rather than timing.

With Cypress, waiting is not something you manage manually. It simply works.

To get working Cypress projects for your portfolio (paid service) and Cypress resume updates, send a message using the Contact Us (right pane) or message Inder P Singh in LinkedIn at https://www.linkedin.com/in/inderpsingh/

Feature 3: Control Over the Network Layer

Testing real-world scenarios often requires control over backend responses. Cypress gives you that control through network interception.

Using the cy.intercept() command, you can intercept any API request made by your application. You can stub responses, return static fixture data, simulate server errors, or slow down responses to test loading states.

This makes your tests deterministic and independent of backend availability. You can also synchronize your tests with API calls by assigning aliases and explicitly waiting for them to complete. This is a reliable way to make sure that your UI has the data it needs before assertions run.

Instead of guessing when data is ready, Cypress lets you wait for exactly what matters.

Feature 4: Cypress Is Not Just for End-to-End Testing

Many teams think of Cypress only as an end-to-end testing tool. While it excels at full user journeys, it is also highly effective for other testing layers.

Cypress component testing allows you to mount and test individual UI components in isolation. This provides fast feedback similar to unit tests, but with real browser rendering and interactions.

Cypress also integrates well with accessibility testing tools. By adding accessibility checks to your test suite, you can catch many common issues early in the development process. While automated checks do not replace manual audits, they form a strong first line of defense.

This flexibility allows teams to use a single tool and a consistent API across multiple testing levels.

Conclusion: Rethinking Your Testing Approach

Cypress is more than a test runner. It redefines how you interact with automated tests. By running inside the browser, handling waits automatically, controlling network behavior, and supporting multiple testing styles, it solves many long-standing automation problems.

Teams that fully embrace these features often see faster feedback, more reliable tests, and greater confidence in their releases.

The real question is not whether Cypress can improve your tests, but which of these features could have the biggest impact on your current workflow.

If you want deep-dive in-person Test Automation and QA projects-based Cypress Training, send a message using the Contact Us (right pane) or message Inder P Singh (18 years' experience in Test Automation and QA) in LinkedIn at https://www.linkedin.com/in/inderpsingh/

December 28, 2025

Playwright with TypeScript: 5 Features That Will Change How You Approach Web Testing

Summary: Playwright with TypeScript is redefining how modern teams approach web testing. By eliminating flaky waits, improving browser communication, and offering powerful debugging tools, Playwright makes automation faster, more reliable, and easier to maintain. First, view the Playwright Test Automation Explained video below and then read on.

In this blog post, I explore five features that explain why so many SDETs and QA are moving away from traditional testing tools.

Introduction

For years, test automation engineers have learned to live with flaky tests, slow execution, and complicated synchronization logic. These issues were often accepted as unavoidable. Playwright, a modern testing framework from Microsoft, challenges that assumption.

Instead of making small improvements on existing tools, Playwright takes a fundamentally different approach. It addresses the root causes of instability and complexity in web testing. When combined with TypeScript, it delivers a testing experience that feels predictable, fast, and developer-friendly.

Let us look at five Playwright features that can genuinely change how you think about web testing.

1. Not Just Another Selenium Alternative

Playwright is architecturally different from older tools. Instead of using the WebDriver protocol, it communicates directly with browsers through a fast WebSocket-based connection. This direct communication removes the traditional middle layer that often causes delays and instability.

Because Playwright talks directly to browser engines, it delivers consistent behavior across Chromium, Firefox, and WebKit on Windows, macOS, and Linux. The result is faster execution and far fewer unexplained failures.

This architectural decision lays the foundation for one of Playwright’s most appreciated capabilities: reliable, built-in waiting.

2. Auto-Waiting That Just Works

One of the biggest sources of flaky tests is timing. Playwright solves this problem at its core through auto-waiting and web-first assertions.

Actions automatically wait for elements to be visible, enabled, and stable before interacting with them. Assertions also retry until the expected condition is met or a timeout occurs. This removes the need for manual sleeps and fragile timing logic.

The benefit goes beyond cleaner code. Auto-waiting lowers the mental overhead for anyone writing tests, making stable automation accessible to the entire team.

To get Playwright projects for your portfolio (paid service) and resume updates, send a message using the Contact Us (right pane) or message Inder P Singh in LinkedIn at https://www.linkedin.com/in/inderpsingh/

3. Testing Beyond the User Interface

Modern applications are more than just UI screens, and Playwright recognizes that. It includes built-in support for API testing and network control, allowing you to manage application state without relying on fragile backend environments.

You can make direct API calls to prepare data before running UI tests or write complete API-focused test suites. Network requests can also be intercepted, modified, blocked, or mocked entirely. This makes tests faster, more deterministic, and easier to debug.

With full control over the test environment, failures become meaningful results instead of random surprises.

4. Trace Viewer That Changes Debugging Forever

Debugging failed tests in CI pipelines has always been painful. Playwright’s Trace Viewer changes that experience completely.

When tracing is enabled, Playwright records every action, DOM snapshot, network request, and console log. The result is a single trace file that can be opened locally to replay the entire test step by step.

This makes it easy to see exactly what happened at any moment during execution. The common excuse of "it works on my machine" quickly disappears when everyone can see the same visual evidence.

5. Parallel, Cross-Browser, and Mobile Testing by Default

Playwright is built for modern development workflows. Tests run in parallel by default, significantly reducing execution time. Cross-browser testing is straightforward, covering Chromium, Firefox, and WebKit with minimal configuration.

Mobile testing is also built in, allowing teams to simulate real devices using predefined profiles. This removes the friction that often causes teams to skip mobile and cross-browser coverage.

By making these capabilities first-class features, Playwright ensures comprehensive testing is no longer a luxury but a standard practice.

Conclusion

Playwright with TypeScript sets a new benchmark for web test automation. Its architecture, auto-waiting, API integration, debugging tools, and built-in scalability solve problems that testers have struggled with for years.

Sticking to older approaches now means accepting unnecessary complexity and flakiness. With Playwright handling the hard problems by default, teams can shift their focus to delivering higher-quality software faster.

If you want deep-dive in-person Test Automation and QA projects-based Training, send a message using the Contact Us (right pane) or message Inder P Singh (18 years' experience in Test Automation and QA) in LinkedIn at https://www.linkedin.com/in/inderpsingh/

December 15, 2025

Java Test Automation: 5 Advanced Techniques for Robust SDET Frameworks

Summary: Learn five practical, Java-based techniques that make test automation resilient, fast, and maintainable. Move beyond brittle scripts to engineer scalable SDET frameworks using design patterns, robust cleanup, mocking, API-first testing, and Java Streams.

Why this matters

Test suites that rot into fragility waste time and reduce confidence. The difference between a brittle suite and a reliable safety net is applying engineering discipline to test code. These five techniques are high-impact, immediately applicable, and suited for SDETs and QA engineers who write automation in Java. First view my Java Test Automation video. Then read on.

1. Think like an architect: apply design patterns

Treat your test framework as a software project. Use the Page Object Model to centralize locators and UI interactions so tests read like business flows and breakages are easy to fix. Use a Singleton to manage WebDriver lifecycle and avoid orphan browsers and resource conflicts.

// Example: concise POM usage
LoginPage loginPage = new LoginPage(driver);
loginPage.enterUsername("testuser");
loginPage.enterPassword("password123");
loginPage.clickLogin();

2. Master the finally block: guaranteed cleanup

Always place cleanup logic in finally so resources are released even when tests fail. That prevents orphaned processes and unpredictable behavior on subsequent runs.

try {
    // test steps
} catch (Exception e) {
    // handle or log
} finally {
    driver.quit();
}

3. Test in isolation: use mocking for speed and determinism

Mock external dependencies to test logic reliably and quickly. Mockito lets you simulate APIs or DBs so unit and integration tests focus on component correctness. Isolate logic with mocks, then validate integrations with a small set of end-to-end tests.

// Example: Mockito snippet
when(paymentApi.charge(any())).thenReturn(new ChargeResponse(true));
assertTrue(paymentService.process(order));

To get FREE Resume points and Headline, send a message to  Inder P Singh in LinkedIn at https://www.linkedin.com/in/inderpsingh/

4. Go beyond the browser: favor API tests for core logic

API tests are faster, less brittle, and better for CI feedback. Use REST Assured to validate business logic directly and reserve UI tests for flows that truly require the browser. This reduces test execution time and improves reliability.

// Rest Assured example
given()
  .contentType("application/json")
  .body(requestBody)
.when()
  .post("/cart/coupon")
.then()
  .statusCode(400)
  .body("error", equalTo("Invalid coupon"));

5. Write less code, express intent with Java Streams

Streams make collection processing declarative and readable. Replace verbose loops with expressive stream pipelines that show intent and reduce boilerplate code.

// Traditional loop
List<String> passedTests = new ArrayList<>();
for (String result : testData) {
    if (result.equals("pass")) {
        passedTests.add(result);
    }
}

// Streams version
List<String> passedTests = testData.stream()
.filter(result -> result.equals("pass"))
.collect(Collectors.toList()); 

Putting it together

Adopt software engineering practices for tests. Use POM and Singletons to organize and manage state. Ensure cleanup with finally. Isolate components with mocking. Shift verification to APIs for speed and stability. Use Streams to keep code concise and expressive. These five habits reduce maintenance time, increase confidence, and make your automation an engineering asset.

Quick checklist to apply this week

Refactor one fragile test into POM, move one slow validation to an API test, add finally cleanup to any tests missing it, replace one large loop with a Stream, and add one mock-based unit test to isolate a flaky dependency.

Send a message using the Contact Us (right pane) or message Inder P Singh (18 years' experience in Test Automation and QA) in LinkedIn at https://www.linkedin.com/in/inderpsingh/ if you want deep-dive Test Automation and QA projects-based Training.

November 24, 2025

Python or C# for Selenium Automation: Which One Should You Pick?

Summary: Choosing a language for Selenium automation shapes speed, maintainability, and integration options. This post compares Python and C# across readability, performance, ecosystem, and real-world trade-offs to help you decide.

Python or C# for Selenium Automation: Which One Should You Pick?

When you start automating browsers—whether for testing or for automating repetitive tasks—Selenium is a go-to tool. But Selenium is only half the equation: the programming language you use determines how fast you develop, how easy the code is to maintain, and what libraries you can plug in.

Python: Fast to Write, Easy to Read

Python is famous for its simple, readable syntax. That makes it a great choice if you want to get tests running quickly or if your team includes newcomers. Scripts tend to be concise, which reduces boilerplate and speeds debugging. If you're new to Python, you can learn it from my Python Tutorials.

Python also has a huge ecosystem. Libraries like Pandas and NumPy are handy when you need to parse or analyze a lot of data. For reporting and test orchestration, Python offers many lightweight options that combine well with Selenium.

Community support is another advantage: you will find tutorials, sample code, and Stack Overflow answers for most problems you encounter.

C#: Strong Typing, Performance, Enterprise Tools

C# is a statically typed, compiled language with deep ties to the .NET platform. For larger test suites or enterprise projects, strong typing helps catch many errors at compile time rather than at runtime. That reduces a class of defects and can make long-term maintenance easier.

As a compiled language, C# often delivers better raw execution speed than interpreted languages like Python. For very large test runs or highly performance-sensitive automation, that can matter.

Development tooling is a strong point for C#. Visual Studio provides advanced debugging, refactoring, and integrated test runners such as NUnit and MSTest. If your organization already uses the Microsoft stack, C# integrates naturally with CI/CD pipelines, build servers, and enterprise practices.

Key Differences

  • Readability: Python wins for concise, beginner-friendly code.
  • Type Safety: C# uses strong typing to surface many bugs earlier.
  • Performance: C# often outperforms Python in raw speed for large suites.
  • Ecosystem: Python excels in data processing and scripting; C# excels in enterprise integration and Windows-based tooling.
  • Tooling: Visual Studio offers mature enterprise-grade tooling for C#, while Python enjoys broad IDE support (VS Code, PyCharm).
  • Learning Curve: Python typically has a gentler learning curve; C# can be more structured and disciplined for large projects.

Which One Should You Choose?

There is no single correct answer. Choose the language that best aligns with your team and goals:

  • Choose Python if you want rapid prototyping, easy-to-read scripts, or tight integration with data-analysis libraries. Python is a great pick for smaller teams or projects that prioritize developer speed and flexibility.
  • Choose C# if your project lives in a .NET ecosystem, you need strong typing and compile-time checks, or you want deep integration with enterprise tooling and Windows environments.

Both languages can drive Selenium effectively. The best decision balances team skills, project scope, and integration needs rather than headline benchmarks alone.

Send us a message using the Contact Us (left pane) or message Inder P Singh (18 years' experience in Test Automation and QA) in LinkedIn at https://www.linkedin.com/in/inderpsingh/ if you want deep-dive Test Automation and QA projects-based Training.

July 25, 2025

Selenium Java Interview Questions and Answers with Selenium 4 code

Here are my Selenium Java Interview Questions and Answers. If you want my complete set of 100+ Selenium Java Questions and Answers as a document, you can message me on LinkedIn at Inder P Singh.



Question: What is Selenium?
Answer: suite of tools for automating web browsers, to automate interactions and verify expected behavior

Question: What are the Selenium components?
Answer: Selenium IDE, Selenium WebDriver, and Selenium Grid

Question: What is Selenium IDE?
Answer: Browser extension or add-on (Chrome, Firefox & Edge) to record scripts, which can run on any browser or Selenium Grid. Used for bug reproduction scripts and website exploration.

Question: How does Selenium WebDriver work?
Answer: It interacts with a web browser or a remote web server. It sends commands to a browser and retrieves the results.

Question: What is the latest version of Selenium WebDriver?
Answer: version 4 (Find element(s) methods, Capabilities and Actions class are different from version 3)

Question: What is Selenium Grid?
Answer: Tool to run Selenium tests on multiple machines simultaneously, reducing the time to test the web application on multiple browsers or operating systems

Question: What are the Selenium advantages?
Answer: free to use, supports multiple programming languages e.g. Java, Python, C#, supports multiple browsers e.g. Chrome, Firefox (each browser has it's own driver)

Question: What are the Selenium limitations?
Answer: no support for testing desktop applications, limited support for testing mobile applications, no inbuilt reporting features

Question: How to get the correct browser driver for a Selenium WebDriver session in Java?
Answer: download the correct browser driver or by using WebDriverManager e.g.
import io.github.bonigarcia.wdm.WebDriverManager;
WebDriverManager.chromedriver().setup();
  
Question: How to create a Selenium WebDriver session in Java?
Answer: by using WebDriver interface e.g.
WebDriver driver = new ChromeDriver();
  
Question: How to create a local Selenium WebDriver in Java?
Answer: by giving path to driver executable and using WebDriver interface e.g.
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
Question: How to create a remote Selenium WebDriver in Java?
Answer: by using RemoteWebDriver class with ChromeOptions e.g.
ChromeOptions options = new ChromeOptions();
WebDriver driver = new RemoteWebDriver(new URL("https://inderpsingh.blogspot.com/"), options);
Question: In Selenium Java, browser navigation can be done by which command(s)?
Answer: driver.get(), driver.navigate().to(), driver.navigate().back(), driver.navigate().forward() and driver.navigate().refresh();

Question: How to maximize the browser window?
Answer: driver.manage().window().maximize();
Example: You can follow me on LinkedIn at https://www.linkedin.com/in/inderpsingh/

Question: How to get the web page title and the URL in the address bar?
Answer: driver.getTitle(); driver.getCurrentUrl();

Question: How to verify the expected result?
Answer: By using JUnit e.g.
Assert.assertTrue(driver.getTitle().contains("Software and Testing Training"));
Question: What are the different locator strategies in Selenium WebDriver with Java?
Answer: WebDriver can find element By id, By name, By class name, By tag name, By link text, By partial link text, By CSS selector or By XPath

Question: Why are relative XPaths preferred instead of absolute XPaths as locators of elements?
Answer: Relative XPaths are more stable than absolute (complete) XPaths, which fail if any part of the path changes even slightly.

Question: What is InvalidSelectorException in Selenium WebDriver with Java?
Answer: It is thrown when an invalid selector is used to locate an element. To fix this issue, check the selector to see if it is correct and that it is being used correctly.

Question: Relative locators in Selenium 4?
Answer: They identify the location, above, below, toLeftOf, toRightOf or near (less than 50 px) another Web Element with a simple(r) locator.
By submitLocator = RelativeLocator.withTagName("button").below(By.id("simpleID"));
Question: How do you chain relative locators in Selenium 4?
Answer: Chaining relative locators means using multiple relative locators e.g.
By login = RelativeLocator.withTagName(By.tagName("button")).below(By.id("Password")).toRightOf(By.id("Cancel"));
Question: How do you interact with an input box in Selenium WebDriver with Java?
Answer:
WebElement i = driver.findElement(By.id("inputId"));
  i.sendKeys("some value" + Keys.ENTER);
Question: How do you clear an input box in Selenium WebDriver with Java?
Answer: By using the clear method. Note it only works if the input element is enabled and editable. e.g.
WebElement i = driver.findElement(By.id("inputId"));
i.clear();
Question: What is the difference between WebDriver close() and quit() methods?
Answer: close() method closes the main browser window but the quit() method (recommended) closes all the browser windows and deletes the session.

Question: How to write the if statement in Java?
Answer: 1) if (condition) { // code block to run if the condition is true } else { // code block to run if the condition is false}
2) variable = (condition) ? expressionTrue : expressionFalse;

Question: How to execute some JavaScript in Selenium with Java?
Answer:
import org.openqa.selenium.JavascriptExecutor;
JavascriptExecutor js = (JavascriptExecutor) driver;
// open a blank tab in the browser
js.executeScript("window.open();");
Question: How do you interact with a link in Selenium WebDriver with Java?
Answer:
WebElement l = driver.findElement(By.linkText("Link Text"));
l.click();
Question: What if the link text is long or can change?
Answer: It is better to use partialLinkText with the stable part of the link text e.g.
WebDriverWait w = new WebDriverWait(driver, 30);
WebElement l = w.until(ExpectedConditions.elementToBeClickable(
  By.partialLinkText("Partial Link Text")));
l.click();
Question: Which element will WebDriver find if there are multiple matching elements for the locator, as in
WebElement a = driver.findElement(By.className("answer"));
Answer: The first matching web element in the DOM

Question: How to find the 2nd or another element instead of the first element?
Answer: By limiting the scope of finding it e.g.
WebElement question2 = driver.findElement(By.id("q2"));
WebElement a = question2.findElement(By.className("answer"));
Question: How to find the 2nd element using a single WebDriver command?
Answer: By using CSS selector or XPath with # for ID and . for class name e.g.
WebElement a = driver.findElement(By.cssSelector("#q2 .answer"));
Question: Which WebDriver command works on any web element?
Answer: click – it clicks the web element in the middle of the element.

Question: How to get the text shown in the browser by an element?
Answer: By using the getText() method e.g.
String t = driver.findElement(By.cssSelector("#q1")).getText();
Question: How to get some attribute's value of a web element?
Answer: By using the getAttribute() method e.g.
String answer = driver.findElement(By.name("answer1")).getAttribute("value");
Question: When invoked on a web element, what does the submit() method do?
Answer: It is used to submit a form. It works on any web element. But in Selenium 4, it is recommended to click the specific form submission button.

Question: How do you handle dropdowns?
Answer: by using Select class
WebElement dropdown = driver.findElement(By.id("dropdown"));
Select s = new Select(dropdown);
s.selectByVisibleText("Option 1");
Question: How to know if a dropdown is multi select dropdown?
Answer: HTML: the select tag contains "multiple" attribute.
d.isMultiple();
Question: Which method works for the multi select dropdown but NOT for the single select dropdown?
Answer: deselectByVisibleText()

Question: How do you verify the state e.g. visible or enabled of a web element?
Answer: By using .isDisplayed() or .isEnabled() methods on the element. .isSelected() method is to verify if a check box, radio button and so on is selected.

Question: How do you handle alerts?
Answer: by using Alert class
Alert a = driver.switchTo().alert();
a.accept();
  
Question: What is NoAlertPresentException?
Answer: It is thrown when there is no alert present on the page. To fix this, verify that an alert is present before interacting with it. Also, follow me in LinkedIn at https://www.linkedin.com/in/inderpsingh/

Question: How do you handle confirmations?
Answer: by using Alert class, a confirmation may be accepted (OK) or dismissed (Cancel)
Alert c = driver.switchTo().alert();
c.dismiss();
  
Question: How can WebDriver handle the JavaScript popup with 2 buttons?
Answer: These are Confirmation (Confirm box) and Prompt alert. Both have accept() (for OK) and dismiss() (for Cancel) methods. Prompt has sendKeys() for text input.

Question: How do you handle frames in Selenium?
Answer: iframes (elements from any domain), switch to iframe e.g.
driver.switchTo().frame("frameName");
  
Question: What is element not found exception in Selenium with Java?
Answer: It can occur when the web element is not present on the web page (e.g. DOM not loaded fully) or not interactable or is within an iframe or shadow root or the element's locator has changed.

Question: How do you interact with an element in an iframe?
Answer:
driver.switchTo().frame("iframeId");
WebElement element = driver.findElement(By.id("elementId"));
element.click();
  
Question: In Selenium with Java, how can you switch to an iframe with duplicate ID & name?
Answer: driver.switchTo().frame() switches to the first iframe with the duplicate ID or name. driver.findElement() can find the iframe as a WebElement to switch to it. The frame index can also be used to switch to it.

Question: In Selenium with Java, what is NoSuchFrameException?
Answer: It is thrown when the frame you are trying to switch to is not present on the page. To fix this, verify that the frame is present on the page before attempting to switch to it.

Question: How to print the data of all the iframes on a web page?
Answer:
for (WebElement f : driver.findElements(By.tagName("iframe"))) {
    String frameData = "iframe id=" + f.getAttribute("id")
        + ", name=" + f.getAttribute("name")
        + ", source=" + f.getAttribute("src");
    System.out.println(frameData);
}
  
Question: What is a window handle?
Answer: It is a unique alphanumeric string of every window. The window handle is generated and controlled by the browser for a single session.

I have explained all these questions and answers and many more Selenium Java questions and answers in my video below. Please view it. Thank you!

May 30, 2023

TestComplete

Great job on starting a new lesson! After reading this lesson, click Next 👉 button at bottom right to continue to the next lesson.

TestComplete is a powerful test automation tool used in software testing. It allows you to automate the testing of your desktop, web, and mobile applications, enabling functional testing, regression testing, and UI testing.

With TestComplete, you can create automated test scripts using a variety of programming languages, such as JavaScript, Python, or VBScript. You can record test scenarios, modify them, and execute tests on different environments and platforms. TestComplete has features like object recognition, data-driven testing, keyword-driven testing, and integration with development and testing tools.

Examples of TestComplete

1. TestComplete is used to automate the testing of your web application. It navigates through different pages, fills out forms, interacts with UI elements, and verifies expected results, ensuring the functionality of your application.

2. TestComplete is used to automate the testing of a desktop application. It performs operations, such as opening files, executing commands, and validating outputs.

3. TestComplete is used to automate the testing of a mobile application. It interacts with different mobile app screens, performs gestures, verifies data inputs, and validates expected behavior across different mobile devices and platforms.

4. A software company uses TestComplete to automate regression testing. It creates test suites with a range of test cases, executes them across different builds and versions, and compares results to identify any regression issues.

Tips for TestComplete

  • Use TestComplete's object recognition capabilities to create stable and maintainable test scripts that can handle UI changes without requiring extensive modifications.
  • Implement data-driven testing by using external data sources or TestComplete's built-in data generators to provide a variety of test data inputs.
  • Organize your test scripts into logical modules and reusable components to enhance test maintenance and reuse.
  • Use TestComplete's integrations with version control systems and test management tools to streamline your test automation processes.

FAQ (interview questions and answers)

  1. Can TestComplete automate the testing of web applications?
    Yes, TestComplete provides features like web object identification, browser automation, and support for various web technologies.
  2. Does TestComplete support mobile application testing?
    Yes, TestComplete allows you to automate the testing of Android and iOS applications, interact with mobile device features, and validate mobile-specific functionality.
  3. Can TestComplete integrate with test management tools?
    Yes, TestComplete can integrate with tools like JIRA and TFS, allowing you to synchronize test cases, and track test execution results.
  4. Is TestComplete suitable for cross-browser testing?
    Yes, TestComplete supports multiple web browsers, allowing you to automate tests across different browser versions.
Remember to just comment if you have any doubts or queries.
TestComplete short tutorial

May 27, 2023

Cookie Testing

Great job on starting a new lesson! After reading this lesson, click Next 👉 button at bottom right to continue to the next lesson.

Cookie Testing is a specialized test that you use to verify the behavior, security, and functionality of cookies in your web application. Cookies are small pieces of data stored on the user's device by websites. They have a crucial role in maintaining session information, personalization, and tracking user activities on the web.  Cookie Testing involves validating cookie creation, expiration, deletion, encryption, and interaction with the application's functionality and user data.

Examples of Cookie Testing

  • You perform Cookie Testing on your web application by verifying if cookies are properly set and retrieved during user sessions, assessing if the session data is maintained correctly.
  • In a web application that offers personalization based on user preferences, you test if the correct personalized content is displayed after the user logs in and their preferences are retrieved from cookies.
  • You conduct Cookie Testing by testing how the web application handles the expiration and deletion of cookies, ensuring that expired or deleted cookies do not cause any unexpected behavior.

Tips for Cookie Testing

  • Understand the purpose and functionality of cookies in the web application to learn the scope of testing and the expected behavior of cookies.
  • Validate if cookies are set correctly with the appropriate values, domain, path, and expiration date.
  • Test scenarios validating cookie creation, expiration, deletion, encryption, and interaction with the application's functionality and user preferences.
  • Validate the behavior of the application when cookies are disabled or blocked by the user's browser.
  • Popular tools for Cookie Testing include Selenium WebDriver, JUnit, and TestNG, which provide capabilities for interacting with cookies, verifying their values, and testing cookie-related functionality.

FAQ (interview questions and answers)

  1. What is the purpose of cookies in a web application?
    They store session information, personalize user experience, and track user activities on the web.
  2. How can you test if a cookie is properly set?
    By inspecting the HTTP response headers or using browser developer tools to view the cookies stored on the user's device.
  3. What should be tested during Cookie Testing?
    Test if cookies are set and retrieved correctly, their values are accurate, expiration and deletion behavior is handled properly, and the application behaves as expected when cookies are disabled or blocked.
Remember to just comment if you have any doubts or queries.


March 09, 2023

SelectorsHub Expert Tutorial - Shadow DOM | iFrame | SVG XPath CSS - SelectorsHub

This is the fourth SelectorsHub tutorial in my SelectorsHub free full course. In this SelectorsHub training, I explain how you can save time by using the features of the SelectorsHub tool, find locators in Selenium etc. for web elements in shadow DOM or iFrame or both shadow DOM and iFrame etc. Learn how to use SelectorsHub to find the correct and unique locators for shadow DOM, iFrame, static SVG images and dynamic SVG images and SelectorsHub user interface customization by viewing SelectorsHub expert tutorial below or read on...

I show how to install SelectorsHub in my previous tutorial so you can install SelectorsHub software testing tool, if you have not already done that.

SelectorsHub Shadow DOM: As I mentioned in the second tutorial, a shadow DOM is outside the main DOM. Basically, a shadow DOM keeps some web elements inside it and the shadow DOM is attached to a web element in the DOM. Only CSS selectors work for shadow DOM and not XPath. You can try it on the SelectorsHub practice page. On it, if you scroll down a little, there is the UserName. Right click it and click on Inspect, which should open developer tools and SelectorsHub pane. In SelectorsHub, it should say that this is inside Shadow DOM, which can't be accessed through XPath so use CSS selector. You can copy the CSS selector to the SelectorsHub smart editor and press the Enter key to find the web element. SelectorsHub should say that one element is matching. SelectorsHub also shows some sample code, that you can copy and modify for use in your test automation script written using Selenium WebDriver etc. 

iFrames: As I mentioned in the second tutorial, iframes are used to make a web page layout. The iframe can be from the same domain or it can be a cross origin iframe. Cross origin iframe means that the iframe is from another domain. If the web element that you inspect is within an iframe, SelectorsHub should say that this web element is inside iframe and you should switch inside iframe to access it through automation. SelectorsHub should give the correct locator of both the web element and the iframe that it is located in.

You can try the cross-origin iframe on this blog, Software Testing Space's Followers widget in the right-side pane. Followers is basically a cross origin iframe. If you right click on one of the followers and click on Inspect, SelectorsHub should recognize that this web element is inside cross origin iframe. How to find XPath of such a web element? For a web element inside cross origin iframe, you can copy selectors by right click on the element, hover to SelectorsHub, copy the XPath and paste XPath in Selenium WebDriver script or your test automation tool. 

SelectorsHub SVG XPath: SVG stands for Scalable Vector Graphics. It is a format for two-dimensional images and it is commonly used in the web pages. Now, SVG elements have a special XPath syntax. SelectorsHub should support both static SVG as well as dynamic SVG. You can try it on the SelectorsHub practice page on the image below "Can you enter name here through automation". On inspecting an SVG, SelectorsHub should say that it's an SVG element and it doesn't support standard XPath format. So, you can copy the XPath generated in a special format by SelectorsHub and use that locator in your test automation script. SelectorsHub also supports dynamic SVG. I have shown dynamic SVG inspection by SelectorsHub tool in my SelectorsHub expert tutorial above. 

SelectorsHub SH selector: SelectorsHub can convert your XPath into CSS selector. SH selector means the SelectorsHub selector that is a CSS selector generated from your XPath by SelectorsHub.

Conclusion: SelectorsHub is a useful tool in web testing for automation testing engineers to enhance their productivity and efficiency, by finding the correct and unique locators for web elements in shadow DOM or iframes or both shadow DOM and iframes and SVG web elements too. Thank you 🙏

Labels: selectorshub, selectors, selenium, locators, tutorial, xpath, locators in selenium, css, selectorshub training, selectorshub tool, xpath selectorshub, xpath in selenium, xpath in selenium webdriver, how to find xpath,in selenium webdriver, how to, selectorshub free full course, tutorial selectorshub, selectorshub shadow dom, iframes, svg, expert

March 04, 2023

SelectorsHub Advanced Tutorial - Dynamic Elements XPath Selectorshub | Generate Multiple Locators and Automation Testing Code

This is the third SelectorsHub tutorial in my SelectorsHub free full course. I explain how to get XPath or CSS selectors for dynamic or difficult web elements and generate multiple XPath and automation testing code. Learn how to use SelectorsHub to find the correct and unique locators for dynamic or difficult web elements by viewing SelectorsHub advanced tutorial below or read on...

SelectorsHub debugger: SelectorsHub has a debugger feature. It is useful when the web element that you are trying to inspect becomes invisible on inspecting. If so, how to find XPath in Selenium WebDriver or other tools for such a web element? You can turn on the debugger in SelectorsHub which stops the web page after 5 Seconds. So, you have 5 seconds in which you need to make that web element visible. I show how this works to get CSS selectors or XPath in Selenium Webdriver or other tools in the above video. I  try to inspect a web element on a website so I right click on it but as soon as I right-click, it disappears. You can find a similar situation on other websites. The solution is that I can use the SelectorsHub debugger feature. In SelectorsHub, there is an icon which says Turn on Debugger. After turning on the debugger, I have 5 seconds to make that web element visible. After 5 seconds, SelectorsHub pauses the web page and I can inspect the web element as usual.

It is possible that the web element disappears within the 5 seconds debugger time. Still, I can use the SelectorsHub tool to find the XPath or CSS selector in Selenium Webdriver or other tools. What I need to do is just click on the icon whose tooltip is Click to customize UI. There I get Debugger start time and I can change it to zero. After changing it to zero, go back to the home screen of SelectorsHub and try again (make the element visible and turn on debugger). This time the debugger should start immediately, pausing the web page. Then I can use SelectorsHub to inspect that element successfully.

Multiple locators: In test automation you don't need just one but different locators in Selenium Webdriver or other tools. In SelectorsHub, I can click the icon whose tooltip says Click to generate automation code or multiple selectors. Then inspect the web elements one by one then I can copy all the XPaths or CSS selectors or if I had set the driver command earlier (read next paragraph), I can even copy the automation testing code or even page object model code. I show this process in the above video to get multiple locators on this blog, Software Testing Space.

Automation testing code: I can not only get multiple selectors like XPath or CSS selectors but I can get the complete command and for that I need click on the icon whose tooltip says Set driver command to append on selectors. Then click on the icon to generate automation code or multiple selectors. You can view the example in the above video.

Verify XPaths: In SelectorsHub usage, you should know about SelectorsHub smart maintenance. I can verify multiple XPaths or I can even verify the complete script by pasting it and giving the XPath command. Again, you can see the example of smart maintenance in the above video.

In conclusion, SelectorsHub is a useful tool for automation testing engineers and web developers to enhance their productivity and efficiency by finding the correct and unique locators for dynamic or difficult web elements and generating multiple XPath and automation testing code. Thank you 🙏

Labels: Locators in selenium, Xpath in selenium webdriver, How to find xpath in selenium webdriver, CSS selector in selenium webdriver, SelectorsHub tutorial, XPath, Selectorshub free full course, Selectorshub tool, Locators in selenium webdriver, Selenium, Locators, Selenium webdriver, Xpath in selenium webdriver, Xpath in selenium, CSS selector, Webdriver, CSS selectors, Automation testing, Test automation

February 27, 2023

SelectorsHub Intermediate Tutorial - Selectorshub XPath | How to use SelectorsHub | CSS SelectorsHub

This is the second SelectorsHub tutorial in my SelectorsHub free full course. SelectorsHub is a powerful tool that allows automation testing engineers and web developers to find the correct and unique locators for web elements in iframes, shadow DOM, XPath for SVG and XPath Axes. Learn how to use SelectorsHub to find such typical locators by viewing my SelectorsHub intermediate tutorial below or read on...

Firstly, to install SelectorsHub extension, users can go to the Chrome web store or the SelectorsHub website, where it provides SelectorsHub links for different browsers. SelectorsHub practice page is a helpful resource that allows test automation engineers to practice finding the locators for web elements in iframes or shadow DOM, SVG and other types of web elements.

Iframes are used to make a website layout, and content can be from the same domain or from another domain, which is called a cross-origin iframe. SelectorsHub can help us find locators for web elements inside iframes. If we inspect a web element using SelectorsHub, it identifies if that web element is inside an iframe. Then, SelectorsHub gives the iframe locator as well as the web element locator. Please view the above SelectorsHub tutorial to see examples of SelectorsHub finding the locators for web element in iframe from the same domain and web element in a cross-origin iframe.

Shadow DOM is a structure that hides or encapsulates web elements. SelectorsHub can find locators for elements in shadow DOM also. Web elements in shadow DOM cannot be accessed using XPath. SelectorsHub identifies if the inspected web element is inside shadow DOM. SelectorsHub gives the CSS selector of such a web element. We can then use CSS selector in Selenium WebDriver or other tools.

SVG stands for Scalable Vector Graphics. SVG is a format for two-dimensional images. SVG stores the image in XML format internally. The benefit of using SVG element in web pages is that it can be scaled to become bigger or smaller with the same quality. SelectorsHub can find the locators for SVG elements. But, SVG doesn't support standard XPath format so, SelectorsHub gives the XPath in a special format for the inspected SVG element.

XPath Axes are useful when we are unable to find a suitable XPath for a web element. XPath Axis is XPath with respect to another web element (with an easier XPath). SelectorsHub supports XPath Axes. On using the Axes button in SelectorsHub, we can inspect the other web element (called Parent in SelectorsHub) and then the difficult web element (called Child in SelectorsHub). SelectorsHub gives the XPath axis for the child element.

In conclusion, SelectorsHub is a useful tool for automation testing engineers and web developers to enhance their productivity and efficiency in finding the correct and unique locators for web elements, especially when working with complicated web pages. Thank you 🙏

December 20, 2020

SelectorsHub Introduction | SelectorsHub tutorial for CSS selectors and XPath locators

This post introduces SelectorsHub, which is a free tool to find correct CSS selectors and XPath locators automatically. CSS selectors and XPath locators can be tough to write for beginners in test automation, like those learning Selenium WebDriver automated testing, or take time to write for experienced web developers and test automators. SelectorsHub automatically suggests complete selectors like CSS selectors, XPath and other web element locators. View SelectorsHub demonstration to find CSS selector like CSS Id and Css Class Selector or read on.

View SelectorsHub demonstration on how to find XPath in Chrome Browser and how to find XPath in Firefox. SelectorsHub is also available for Edge and Opera browsers.

SelectorsHub may help you improve XPath and CSS selectors writing skills. It offers choices of selectors and locators with the number of occurrences of each. SelectorsHub works with shadow DOM and svg element. It also gives the error message if case of any mistake in your written selector. SelectorsHub's user interface may be customized, if you want. View the demonstration of SelectorsHub features and benefits.

For details, check out What is SelectorsHub. You may also contact Sanjay Kumar, the inventor of SelectorsHub. Thank you.

August 09, 2020

Selenium Python Tutorial 14 | Selenium Python Unittest Framework with POM | Selenium Unit Testing

This is the next tutorial in the Selenium Python Tutorials for Beginners. It deals with Python Automation Testing with Selenium WebDriver Python. This Selenium Python beginner tutorial deals with the Selenium Python Unittest framework and Selenium unit testing. First, view the Selenium Python Unit Test Tutorial. Then read on.

Here is my Selenium Python example, which is based on the example that I showed in my Selenium Python tutorial 13. This Page Object Model (POM) based Selenium Python example uses the Python unit test framework to run the test methods in a test class. I put explanations in the comments within the code (lines starting with #).

# Test_Cases>WikipediaTestClass1.py
# Selenium WebDriver Python coding
# Import unittest library for working with Selenium Unit Testing Python.
import unittest
from selenium import webdriver
# Import the page object files in the Pages directory.
# The POM files are MainPage.py and EnglishPage.py. Their code is in Selenium Python tutorial 13.
from Pages.MainPage import MainPage
from Pages.EnglishPage import EnglishPage

class WikipediaTestClass1(unittest.TestCase):
    exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
    base_URL = "https://www.wikipedia.org/"

    # First independent test method to test the main page
    def test_main_page(self):
        driver = webdriver.Firefox(executable_path=self.exec_path)
        driver.get(self.base_URL)
        mp = MainPage(driver)
        mp.test_title()

    # Second independent test method to test the english page
    def test_english_page(self):
        driver = webdriver.Firefox(executable_path=self.exec_path)
        driver.get(self.base_URL)
        mp = MainPage(driver)
        mp.click_english_link()
        ep = EnglishPage(driver)
        ep.search_text()

# Run all test methods using the unit test library.
# In PyCharm, click the green arrow next to this if statement and then click Run 'WikipediaTestClass1'.
if __name__ == "__main__": unittest.main()

Next, in this Selenium WebDriver Python tutorial, let us see the Selenium Python example to skip test methods using Selenium Python. I modified the above Python script to skip test methods.

# Test_Cases>WikipediaTestClass2.py
# Selenium WebDriver Python coding
import unittest
from selenium import webdriver
from Pages.MainPage import MainPage
from Pages.EnglishPage import EnglishPage

class WikipediaTestClass2(unittest.TestCase):
    # run_all_test_cases variable is used to skip unit tests conditionally.
    run_all_test_cases = False
    exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
    base_URL = "https://www.wikipedia.org/"

    # If you want to skip unit test with condition, use the skipIf unit test annotation.
    @unittest.skipIf(run_all_test_cases==False, "This is a medium priority test case.")
    def test_main_page(self):
        driver = webdriver.Firefox(executable_path=self.exec_path)
        driver.get(self.base_URL)
        mp = MainPage(driver)
        mp.test_title()

    # If you want to skip unit test, uncomment the unit test annotation.
 # @unittest.SkipTest
    def test_english_page(self):
        driver = webdriver.Firefox(executable_path=self.exec_path)
        driver.get(self.base_URL)
        mp = MainPage(driver)
        mp.click_english_link()
        ep = EnglishPage(driver)
        ep.search_text()

if __name__ == "__main__":
    unittest.main()

Finally, let us see the Selenium Python example with unit testing setup method and unit testing teardown method. I added these unit test special methods, the unit testing set up method and and unit testing tear down method to the above Python script.

# Test_Cases>WikipediaTestClass3.py
# Selenium WebDriver Python coding
import unittest
from selenium import webdriver
from Pages.MainPage import MainPage
from Pages.EnglishPage import EnglishPage

class WikipediaTestClass3(unittest.TestCase):
    exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
    base_URL = "https://www.wikipedia.org/"
    driver = webdriver.Firefox(executable_path=exec_path)

    # unit test setUp method runs before every test method. 
    #  Notice the @classmethod unit test annotation.
    @classmethod
    def setUp(self):
        print("This method runs before every test method.")
        self.driver.get(self.base_URL)

    # unit test tearDown method runs after every test method. 
    #  Notice the @classmethod unit test annotation.
    @classmethod
    def tearDown(self):
        print ("This method runs after every test method.")

    def test_main_page(self):
        mp = MainPage(self.driver)
        mp.test_title()

    def test_english_page(self):
        mp = MainPage(self.driver)
        mp.click_english_link()
        ep = EnglishPage(self.driver)
        ep.search_text()

if __name__ == "__main__":
    unittest.main()

Want to see the Python unit test library run the above Selenium Python examples? Then view my Python Selenium UnitTest Tutorial and Selenium Python Unit Testing with POM Tutorial. Thank you.

August 02, 2020

Selenium Python Tutorial 13 | Framework | Selenium Python Page Object Model | Python selenium POM

Moving on to the next tutorial in the Selenium Python Tutorials for Beginners. It deals with Python Automation Testing with Selenium WebDriver Python. This Selenium Python beginner tutorial explains Selenium Python Page Object Model, also known as the POM framework. Not using the Selenium Python POM framework results in lower Python code readability and code duplicity. We can implement Python Selenium POM by creating separate Python files for the web page and the test logic. First, view the Selenium Python Page Object Model Tutorial Then read on.

Selenium Python POM implementation has the following steps:
  • Create separate directories for web pages and test cases. Optionally, create separate directories for browser drivers, logs and screenshots.
  • In the web pages directory, create a separate Python file for each web page. This Python file should contain the code for web page operations, web page locators and title etc.
  • In the test cases directory, create a separate Python file for each test case. This Python file should contain only the test logic, which consists of test steps and expected results' validations.
Here is my Selenium Python Page Object example. This is based on the Selenium Python example that I showed in the Selenium Python tutorial 1. I created the directories Test_Cases and Pages by right clicking the project in PyCharm IDE > New > Directory. Then, I created the Python files within the relevant directories by select the directory > right click > New > Python File. Within the Python code, I put explanations in the comments within the code (lines or phrases starting with #).

# Test_Cases>WikipediaTest1.py
# Selenium WebDriver Python coding
from selenium import webdriver
from Pages.MainPage import MainPage
from Pages.EnglishPage import EnglishPage
exec_path = r"E:\Training\SeleniumPython\Downloads\geckodriver-v0.26.0-win32\geckodriver.exe"
driver = webdriver.Firefox(executable_path=exec_path)
base_URL = "https://www.wikipedia.org"

def set_up():
    driver.get(base_URL)

# Test logic containing the test steps and expected results' validation
def test_main_page():
    mp = MainPage(driver)
    mp.test_title()
    mp.click_english_link()

# Test automation logic (test steps and expected results' validation)
def test_english_page():
    ep = EnglishPage(driver)
    ep.search_text()

set_up()
test_main_page()
test_english_page()

# Pages>MainPage.py
# Selenium WebDriver Python coding
from selenium.webdriver.common.by import By
# Import statements for Explicit Wait or WebDriverWait Python
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E

class MainPage():
    # Put the title and web page locators.
    title = "Wikipedia"
    english_partial_link_text = "English"
    wait_time_out = 5 # for explicit wait

    # init method will be executed automatically when the MainPage object is created.
    def __init__(self, drv):
        self.drv = drv
        self.wait_variable = W(self.drv, self.wait_time_out)

    # Now, add methods for automation test logic.
    # test_title is a web page operation in the MainPage for expected result validation.
    def test_title(self):
        assert self.title in self.drv.title

    # click_english_link is also a web page operation in the MainPage.
    def click_english_link(self):
        self.wait_variable.until(E.element_to_be_clickable((By.PARTIAL_LINK_TEXT, self.english_partial_link_text))).click() 

# Pages>EnglishPage.py
# Selenium WebDriver Python coding 
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as W
from selenium.webdriver.support import expected_conditions as E

class EnglishPage():
    # Put the web page locators and search term.
    search_id_locator = "searchInput"
    term = "Software"
    wait_time_out = 5 # for WebDriverWait Python

    # The class init method is also called the constructor.
    def __init__(self, drv):
        self.drv = drv
        self.wait_variable = W(self.drv, self.wait_time_out)

    # automation test logic
    def search_text(self):
        input_box_element = self.wait_variable.until(E.presence_of_element_located((By.ID, self.search_id_locator)))
        input_box_element.send_keys(self.term)
        input_box_element.submit()
        # Expected result validation
        self.wait_variable.until(E.title_contains(self.term))

Want to understand how the Python code above works? And how to implement logging and screenshots in the POM framework easily? Then please view my Selenium Python POM Tutorial. Thank you.