Master Software Testing & Test Automation

Selenide Automation: An Introduction to the Tool

Selenide

Getting Started with Selenide

v2 3f8bo fswng

Selenide is a popular open-source automation testing framework for web applications. It is built on top of Selenium and provides a more concise and intuitive API for writing automated tests. In this section, we will cover the basics of getting started with Selenide.

Why Choose Selenide for UI Automation?

Selenide stands out for its simplicity and effectiveness in UI automation. Rather than bogging testers down with manual browser management and endless configurations, Selenide handles much of the heavy lifting behind the scenes. For example, it automatically manages browser sessions and intelligently waits for web elements to appear or update, so you don’t have to write complex wait conditions or worry about flaky timing issues.

Another highlight is Selenide’s smart error handling. If a test fails, Selenide automatically captures and stores a screenshot of the browser, which is invaluable for diagnosing problems quickly.

From a code organization perspective, Selenide encourages the use of the page object pattern—a best practice in UI testing. This pattern allows you to create classes that represent whole pages or specific areas of your application. If something about the UI changes, you’ll only need to update your page object, and all your related tests will work seamlessly. This reduces maintenance headaches and keeps your test code easy to read and update.

By focusing only on what matters for the test at hand, Selenide lets you write clean and readable code. Its API is intuitive and minimizes boilerplate, meaning that test scripts are both short and expressive. Whether you are updating a locator or tweaking a user flow, the changes remain straightforward and clear.

Key Advantages of Selenide for UI Automation

Selenide stands out among UI automation testing tools thanks to its thoughtful design and developer-friendly features. If you’ve found yourself wrangling with Selenium’s boilerplate or chasing down elusive test failures, Selenide offers a breath of fresh air.

Here’s why testers gravitate toward Selenide:

  • Automatic Browser Management: Selenide opens and closes browser windows for you, so there’s no need for manual setup or teardown code. This streamlines your test cases, letting you focus on what matters: verifying your application.
  • Built-in Waiting: Forget about hunting down just the right amount of sleep or explicit waits—Selenide’s smart waiting strategy automatically waits for all elements to appear or reach the desired state, dramatically reducing flaky test failures.
  • On-the-Spot Diagnostics: Selenide captures screenshots and page sources by default when something goes wrong. This means you can instantly see what was happening on the page at the moment of failure, making bugs much easier to track down.
  • Clean and Intuitive API: By abstracting away much of the repetitive WebDriver code, Selenide enables you to write concise, readable, and expressive tests. Most interactions boil down to simple, self-explanatory commands.
  • Flexible Configuration: Whether you need to adjust file storage locations, switch browsers, or tweak timeouts, Selenide offers multiple ways to configure these options—via property files, system properties, or programmatically in your Java code. This flexibility is particularly handy for adapting to different environments or integrating with your CI system.

In a nutshell, Selenide focuses on developer experience. It minimizes overhead, elegantly handles common pain points in UI testing, and gives you the tools to write clear, robust tests.

Switching Browsers in Selenide

By default, Selenide will use Google Chrome to run your tests. However, you might want to run your tests on other browsers like Firefox or Edge to ensure wider compatibility. Selenide makes browser switching flexible and straightforward. You can change the browser in a few different ways:

  • In your code: Set the desired browser before your tests run by assigning Configuration.browser = "firefox"; (or another supported browser in your configuration class or setup method.
  • Via command line: When launching your tests, add a system property like -Dselenide.browser=firefox to select the browser at runtime.
  • Using a configuration file: Place selenide.browser=firefox in a selenide.properties file in your project to set the browser across all runs.

This flexibility means you can easily configure your tests to run across multiple browsers—manually on your local machine or automatically as part of your CI/CD pipeline, without required changes to your test code.

Installation and Configuration

To start using Selenide, you need to have Java and Maven installed on your system. Once you have installed these dependencies, you can add the Selenide dependency to your Maven project by adding the following code to your pom.xml file:

<dependency>
    <groupId>com.codeborne</groupId>
    <artifactId>selenide</artifactId>
    <version>5.23.0</version>
</dependency>

After adding the dependency, you can configure Selenide by creating a SelenideConfig class and setting the necessary options. For example, you can set the default timeout for element searches using the following code:

import static com.codeborne.selenide.Configuration.*;

public class SelenideConfig {
    static {
        timeout = 10000;
    }
}

Basic Commands and Syntax

Selenide provides a simple and intuitive syntax for interacting with web elements. Here are some basic commands and syntax that you can use with Selenide:

  • open(url) – opens the specified URL in the browser
  • $(selector) – finds the first element that matches the specified selector
  • $$() – finds all elements that match the specified selector
  • element.shouldBe(condition) – waits for the element to satisfy the specified condition
  • element.click() – clicks on the element
  • element.setValue(value) – sets the value of the element to the specified value
  • element.getText() – gets the text of the element

Selenide also provides a WebDriver instance that you can use to perform more advanced actions. For example, you can use the WebDriver instance to navigate to a different page using the following code:

import static com.codeborne.selenide.Selenide.*;

public class ExampleTest {
    @Test
    public void test() {
        open("https://www.google.com");
        WebDriver driver = getWebDriver();
        driver.navigate().to("https://www.selenium.dev/");
    }
}

In summary, Selenide is a powerful and intuitive Test Automation Frameworks for web applications. By following the steps outlined in this section, you can get started with the automation tool and start writing automated tests for your web applications.

Locating and Interacting with Elements

Selection Methods

The tool provides a variety of methods to locate elements on a web page. These methods include find, by, id, name, class, and xpath.

The The find method is used to locate an element by its tag name. The by method is used to select an element by its attribute. The id method is used to select an element by its id attribute. The name method is used to select an element by its name attribute. The class method is used to select an element by its class attribute. The xpath method is used to select an element using an XPath expression.

Selenide also provides a $(...) method that can be used to select an element based on a CSS selector.

Actions on Elements

Once an element has been located, Selenide provides a variety of methods to interact with it. These methods include click, type, val, text, attr, setValue, and click().

The The click method is used to simulate a mouse click on an element. The type method is used to simulate typing into an input field. The val method is used to retrieve the value of an input field. The text method is used to retrieve the text of an element. The attr method is used to retrieve the value of an attribute of an element. The setValue method is used to set the value of an input field. The click() method simulates a mouse click on an element without waiting for it to become clickable.

The automation tool also provides a $$(...) method that can be used to select multiple elements based on a CSS selector.

Using the Page Object Pattern

The Page Object pattern is a widely adopted design approach in automated UI testing. It helps organize test code by modeling web pages or their components as objects within your tests. The key idea is to encapsulate the structure and behavior of each page (or part of a page) in its own class. This way, if something about the page changes—like a button’s selector or the layout of a form—you only need to update one place in your codebase.

With Selenide, implementing the Page Object pattern is straightforward. You define Java classes representing your web pages, exposing methods corresponding to user actions, such as performing a search or retrieving a result.

For example, a class representing a search page might provide methods to load the page and perform a search. Another class could represent the results page, giving you methods to retrieve results or interact with result items. Each Page Object class internally uses Selenide’s concise selectors and actions—like $(…) and .shouldBe(visible)—to interact with the page elements.

Here’s a brief outline of how you might set up your Page Objects with Selenide:

  • Page Object Class: Encapsulates one web page or a significant section of a page.
    • Provides methods to perform user actions (e.g., openPage(), submitForm()).
    • Exposes methods to validate page state or extract information.
  • SelenideElement Wrapping: Internally, the class uses Selenide selectors or SelenideElement objects to represent interactive elements.
  • Usage in Tests: In your test cases, you create instances of these page objects, interact with their methods, and assert results. This makes tests easy to read and maintain.

The primary benefit is reduced duplication and greater resilience to UI changes. If the structure of a page or an element locator changes, you update it only in the relevant Page Object class rather than hunting through all your test code. This results in cleaner, more maintainable, and more readable automated tests.

By leveraging this pattern, Selenide tests become as robust as those written with Selenium WebDriver but with a more streamlined syntax and improved readability.

Assertions and Conditions

Element State Assertions

The tool provides various methods to check an element’s state. These methods use the should keyword to assert that an element meets a certain condition. The should keyword is followed by a condition that describes the element’s state.

The should keyword can be used with a variety of conditions, including be, have, visible, exist, selected, enabled, appear, and empty. For example, should(be(visible)) asserts that an element is visible. Similarly, should(have(text("example"))) asserts that an element has the text “example”.

Conditional Operations

Selenide also provides conditional operations that can be used to perform actions based on the state of an element. These operations use the should keyword to wait for an element to meet a certain condition before performing an action.

The should Keywords can be used with a variety of conditions, including be, have, visible, exist, selected, enabled, appear, and empty. For example, shouldBe(visible) waits for an element to become visible before continuing.

In addition to the should keyword, the tool provides the waitUntil method, which can be used to wait for an element to meet a certain condition before continuing. The waitUntil method takes a condition as an argument and waits for the element to meet that condition before continuing. For example, waitUntil(Condition.visible) waits for an element to become visible before continuing.

Overall, the tool provides a powerful set of assertions and conditions that can be used to check an element’s state and perform actions based on that state. These features make it easy to write reliable and robust tests that can handle a variety of scenarios.

Advanced Techniques and Best Practices

Working with Collections

When working with collections of elements in Selenide, it is important to understand the different methods available to interact with them. The ElementsCollection class provides several useful methods, such as filterBy, exclude, and findBy.

One best practice when working with collections is to use the shouldHaveSize method to verify the expected number of elements in the collection. This helps ensure that the test checks the correct set of elements.

Another helpful technique is to use the each method to iterate over each element in the collection and perform a set of actions on each one. This can be helpful when performing repetitive actions on a set of elements.

File Uploads and Downloads

The test automation tool provides built-in support for file uploads and downloads. The method can be used to select a file from the classpath to upload a file. The The uploadFile method can be used to select a file from the local file system.

To download a file, the download method can be used to download a file from a URL. The download() method can download a file from a link on the page.

Customizing The Tool Behaviors

The tool provides several ways to customize its behavior. The Configuration class can be used to set global configuration options, such as the timeout for explicit and implicit waits.

For more granular control, the  proxyElement method can wrap an element in a proxy that allows for custom behavior. This can be useful for implementing custom wait conditions or other behaviors.

Overall, these advanced techniques and best practices can help testers to write more effective and efficient tests using the automation tool. By understanding the different methods and options, testers can optimize their testing workflow and ensure their tests are reliable and accurate.

Understanding Test Failures

When automated tests fail, pinpointing the exact reason can sometimes feel like searching for a needle in a haystack. Fortunately, Selenide is designed to make this process as straightforward as possible.

Whenever a test fails—whether due to an incorrect search term or unexpected behavior—Selenide provides detailed error messages that indicate precisely which assertion did not pass. These error messages include information about the element being interacted with and the actual state observed during the test.

In addition to clear error messages, Selenide automatically captures both a screenshot and the page’s HTML source at the moment of failure. This means you can visually inspect what was displayed or analyze the underlying markup, helping you quickly understand whether the issue lies in the test itself or in the application under test. For example, if your test was expecting a certain text to appear but something else is displayed, the screenshot can immediately reveal the discrepancy.

This combination of descriptive errors, screenshots, and page sources significantly reduces the time and effort needed to diagnose failures, making your debugging workflow both faster and more reliable.

What Happens When a Selenide Test Fails?

Error handling is a crucial part of automated testing, and Selenide makes troubleshooting straightforward when things go awry. Selenide gives you immediate, useful feedback if a test fails—say, your assertion doesn’t match the actual result.

Whenever an assertion fails, Selenide automatically captures a screenshot and the full page source at the moment of failure. This means you get a clear snapshot of exactly what was on the screen (and in the DOM) when things broke. You’ll see:

  • The specific element your test interacted with or asserted against
  • The actual versus expected values (such as text, visibility, or attribute content)
  • Quick-access links to the screenshot and HTML snapshot

This detailed error output can save you a lot of time tracing bugs. For example, you might spot that an element’s text was different than you expected or that a button was disabled instead of enabled. The visual snapshot often makes the problem obvious—maybe you typed the wrong search term, or the web page layout unexpectedly changed.

In some cases, this process might reveal that your test uncovered a real issue in your application—such as a regression or unexpected UI change—rather than a problem with the test logic itself. Either way, Selenide provides all the context you need to diagnose and resolve test failures quickly.

Leveraging Page Objects for Cleaner, Maintainable Tests

When it comes to building robust UI tests, the Page Object pattern emerges as a real game-changer. Instead of scattering selectors and interaction code throughout your tests, Page Objects let you encapsulate the logic for an entire web page—or a section of it—into dedicated classes. This approach delivers two big benefits:

  • Simplified Maintenance: If a change is made to the way a web page works (say, a button gets a new selector or a field is moved), you only need to update the relevant Page Object class. Instantly, all the tests relying on that class are up to date. No more hunting through dozens of test files to make the same fix over and over.
  • Improved Readability: Tests that use Page Objects tend to read like clear, high-level descriptions of user actions. Instead of cryptic chains of selectors, you’ll see expressive calls like loginPage.signInWith(validUser) or searchResults.getFirstResultText(). This makes your tests easier to understand for anyone unfamiliar with the underlying HTML.

By modeling your pages as objects, you reduce duplication, make tests less brittle, and allow yourself to refactor quickly—freeing you up to focus on meaningful test logic rather than repetitive UI plumbing.

Customizing Screenshot Storage and Other Defaults

Selenide is designed to work smoothly right out of the box, automatically saving screenshots for failed tests, typically to the build/reports/tests folder by default. However, test environments and project structures can vary, so fine-tuning these defaults can be essential for seamless integration with your workflow.

You can adjust settings like the screenshots folder and other configuration options in several ways:

  • Properties File: Place a selenide.properties file at the root of your classpath (for example, in src/test/resources for the project). Define properties here using the format selenide.<propertyName>. This lets you maintain project-level settings within your version control.
  • System Properties: Pass system properties using the same naming convention as fields in the Configuration class, prefixed with selenide.. These are useful for overriding values at runtime, such as from the command line or within CI pipelines.
  • Programmatic Configuration: For immediate control, set configuration properties directly in your test code by modifying the Configuration class. You can do this at test startup (e.g., in @BeforeEach methods), within specific test classes, or by using your custom test runners. This approach takesthe  highest priority and enables you to tweak settings specifically for specific tests or execution environments.

With these flexible options, you can ensure Selenide adapts to virtually any project structure or CI/CD system, keeping your reports, screenshots, and downloads organized precisely where you want them.

Share it :

Leave a Reply

Discover more from Master Software Testing & Test Automation

Subscribe now to keep reading and get access to the full archive.

Continue reading