What’s up Guys! Welcome to automationcalling.com

10 MIN READ

HomePage

There are a lot of tools in the market who uses Selenium as a base and create a wrapper on top of it for more customization, better readability of code and less maintenance for eg., Watir, Protractor etc., To know more details about Watir please refer Cross Browser Automation Testing using Watir and Protractor please refer Automated Cross Browser Testing with Protractor & Selenium.

We are going to take a look on another popular library “Selenide”, that uses selenium as a base.

Selenide is an open source library for test automation powered by Selenium WebDriver. In fact, this library is addressed and more focus on automation testing especially Concise API and stable tests. Selenium testing with Selenide has been very convenient and effective.

Benefits of Selenium testing with Selenide

Selenide supports multiple languages:

  • Java
  • Scala
  • Groovy
  • Clojure

Integration Options are:

  • Can use BDD
  • Can use with JUnit, TestNG, JBehave, Cucumber, Serenity
  • Can use to integrate with Extent Report, Allure Report etc.,
  • Supports Cross Browser Parallel execution
  • Page Objects

To know about which companies perform Selenium testing with Selenide, please refer this link.

Why do we still need Another Wrapper?

There are several testing libraries around Selenium WebDriver, but what makes Selenium testing with Selenide special?

Below are some of the major attractions of performing Selenium testing with Selenide.

  • Concise UI Test: Selenide API consist of very few classes which were build on top of Selenium. Implementing Automation test code using Selenide is clean, better readability and ease to use.
  • AJAX challenges: The beauty of AJAX is to make the web page retrieve data from server without loading the entire page. For eg., if you add the entry in the form, assume at left pane in the page the recent added data is displayed then the whole page not getting refreshed and return the data. When automate this in web page, we often we end up the issue “No Such Element Exception”. To handle this, different wait method should be applied in Selenium WebDriver. In Selenide, this is already addressed and no additional code is required.
  • Time out issues: While running automation sometime we end up with timeout issue for eg.,loading web page takes time or finding elements takes time. This is handled in Selenide well, by default it waits 4 seconds if uses Selenide Inbuild methods. On top of it, you can still configurable more secs for better synchronization.
  • Automated Screenshots: By Default failed test Selenide takes snapshot unlike Selenium WebDriver. In Selenium WebDriver you need to add explicit code. Please take a look on below snapshot which actually takes snapshot and share the location where it’s located.

033_screenshots

  • StaleElementException: There are two reason this exception occurs:
    • The element no longer attached in the DOM but you code might have referenced to the element
    • The element has been deleted or modified with same id or same attribute completely.
  • Concentrate on Business Logic: Just focus on what needs to be tested for your business logic, rest Selenide will take care for eg., Conditions, validation, synchronization, timeout issues, browser configuration etc.,
  • More focus on Testing: Selenide developed focus on Automation Testing on top of Selenium WebDriver.

The current release version of Selenide is 5.1.0. Let’s take a look on all the key libraries used by Selenide.

001_Tranisent_DependenciesAs Selenide was developed as a wrapper on top of Selenium, here are some key libraries that you may find familiar if you have already used Selenium frameworks:

 

selenium-java: Used latest version of selenium Java API
selenium-server: to support selenium Grid for parallel execution
webdrivermanager: to support inbuild browser configuration to avoid initialization
testng: Support TestNG framework
commons-fileupload: To handle file uploads capability to your servlet and web application
junit: Support JUnit Framework

The beauty of Selenide is:

  • You can still use Selenium WebDriver Directly
  • You can use any webdriver instance

Kick-Starting Selenium Testing With Selenide

Selenide group offer 3 simple things to kick start your test automation, which are:

  • Open the page
  • $(element).doAction()
  • $(element).check(condition)

For e.g., Please take a look on below snapshot:

The below syntax representation would help you understand the syntactical difference between Selenium WebDriver and Selenide.

Selenium WebDriver Selenide
driver.get(“https://www.lambdatest.com/) Open(https://www.lambdatest.com/)
driver.findElement(By.className(“#submit”)).click() $(“#submit”).click();

 

String actualResult=driver.findElement(By.className.message).getText()

//Conditions

If(text.contains(actualResults)

 

$(“.message.”).shouldHave(text(“Hello”))

You can observe the readable and concise syntax used for Selenide.

Selenium Testing With Selenide: Setting up the Environment

The pre-requisites are JDK 1.8.0 and Intellij.

●        For installing Java, minimum JDK 8 is required,  to download in official site click here.

After download, installation is very simple and self-explanatory to complete.

After installation is complete, you would have to setup the classpath so that the program understand where the java is located in your machine.

This can be done in windows operating system by searching for “Environment Variables” and selecting “Edit System Environment Variables”. Create JAVA_HOME in system variable and PATH as mentioned in the below snapshot.

Create JAVA_HOME in System variable and update the value where the Java is located in your machine.

003_Java_Home

Now, we need to edit the Path system variable and add JAVA_HOME in it so that all run time programs are able to detect Java in your machine. Make sure you append the value after adding a semicolon.

004_Adding_JavaHome_in_Path

To verify, if JDK is properly installed or not. You need to supply the below command:
java -version”

005_Verifying_Java_Version

Kudos! You just installed JDK successfully on your machine.

Selenium testing with Selenide – Download IntelliJ and Setting up Maven project

There are multiple IDE’s available in the market. In this article, I recommend using IntelliJ for Selenium testing with Selenide. IntelliJ is a free, open-source Java IDE(Integrated Development Environment) for developing Java, Kotlin based software programming. This tool has Community and Ultimate version, community version of IntelliJ can be downloaded from here.

After download Intellij, the installation part is pretty much easy, just follow with instruction and keep going with default parameter and complete it.

Open Intellij and select “Create New Project” from Dashboard window.

006_IntelliJ_Launch_Page

For this Article, I would prefer to use a “Maven” project. Select the particular Java version that we installed and click on Next with Default parameters.

007_Select_Maven

Enter values in necessary fields like GroupID, ArtifactID and keep it as default version.

008_projectName

Leave the project name and select where your project is to be located.

The created Selenide project is displayed in IntelliJ as mentioned below.

009_Maven_model

Add Selenide Maven Dependency as mentioned below:

<dependencies>
    <!-- https://mvnrepository.com/artifact/com.codeborne/selenide -->
    <dependency>
        <groupId>com.codeborne</groupId>
        <artifactId>selenide</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

Feel free to add the required transient dependencies in your class path. As I previously mentioned, selenide library supports TestNG, JUnit frameworks.

Selenium Testing With Selenide- Sample Code(Self Explanatory)

@Test
public void verifyStartTestingButton() {
    //Launch Lambdatest page
    open("https://www.lambdatest.com/");
    //use CSS Selector to find element and click for navigating register page
    $(".nav>li.login>as").click();
    //Verifying Page title using Selenide reusable method
    Assert.assertEquals("Sign up for free | Cross Browser Testing Tool | LambdaTest - LambdaTest", title());
    //Verifying text "Sign up"
    $(".signup-titel").shouldHave(text("SIGN UP"));
    //Feeding value to the text using .val
    //Feeding value to the text using sendkeys
    $(By.name("organization_name")).val("org");
    $(By.name("name")).sendKeys("Name");
    $(By.name("email")).sendKeys("test@gmail.com");
    $(By.name("password")).sendKeys("test1234");
    //using shortcut to signup instead of clicking button
    $(By.name("phone")).val("13452").pressEnter();
    //Capturing actual results and verifying with expected one using collections
    $$(".error-mass").shouldHave(
            texts("This email is already registered",
                    "Please enter a valid Phone number",
                    "To proceed further you must agree to our Terms of Service and Privacy Policy"));
}

 

In the above example: 

  • Login to LambdaTest Page.
  • Click on Register button.
  • Enter invalid value in org, fullname, work email, desired password and phone to target on mandatory fields to make sure it returns error.
  • Finally capture all errors throws in the page using collections.

As compared in previous section, testing with Selenide is lightweight, ease to use and offers better readability with comparison to Selenium. I didn’t include browser configuration or any pre-requisites like @BeforeClass or @BeforeMethod and not used loops to iterate and get content of error message.

To run your local browser simply, just use url and write basic test as mentioned above.

The Default browser is “chrome” browser, in case you haven’t declared any configuration. Here is the test result for local test execution without browser configuration.

011_default_chrome

010_Local_Instance_Test_Results

Wish to perform Selenium testing with Selenide on a different browser?

To run the same test in other browsers is also pretty simple. For example, in case you want to use Firefox browser I configured as below.

Firefox_config

To know more about browser configuration and how to know Selenide support which browsers, please take a look on below snapshot.

013_More_Browser_config

Reusable Commands in Selenide

Here we deep dive on Selenide reusable commands:

014_Simple_Test

In above simple reusable method, we are going to take a look on what is “$” and “$$” and selenium action and conditional commands.

$ and $$ Method Definitions:

In Selenide Terminology:

  • $ Indicate finds Single Element
  • $$ Indicate finds More than one Elements used Collections

015_Element_Locators016_elements_locators_collections

In above snapshot, an argument in Selenide method accepts different types:

  • WebElement (Element)
  • cssSelector as String
  • Xpath as String
  • SeleniumSelector as By (for eg., By.xpath(“”))

For the cssSelector and xpath, you can assign locator directly as string which is ease to use and maintain locators.

Conditions:

017_conditions

In above sample program, we use the following condition to verify the results without assertion:

  • $(".signup-titel").shouldHave(text("SIGN UP"));
    • In this method, I verify “SIGN UP”text exists which I use “shouldHave” method
    • “.signup-title” is cssLocator
    • $ indicates find/return single element
  • $$(".error-mass").shouldHave(
    
    texts("This email is already registered",
    
                    "Please enter a valid Phone number",
    
                    "Another condition to verify….."));
  • Used CSS Selector to locate error message which returns more than one error.
  • shouldHave is method to verify the condition the necessary text appears.
  • texts accepts argument in array where you can pass multiple expected text conditions.
  • This method should verify condition between actual and expected results.

In build, the above condition like shouldbe, ShouldHave exhibits smart waiting capabilities:

  • shouldbe(“visible”)
  • shouldHave(Text(“Hello Test”))
  • shouldNotBe(“selected”)
  • should(“disappear)

By default, $.should() Method waits up to 4 seconds. However, if you wish to change the timeout then you can customize it in the following ways:

  • Configuration.timeout=4000 (Millisecs)
  • Mvn –Dselenide.timeout=8000 //mvn specific command

For Verifying expected text in collections:

$(By.xpath("//p[@class='error-mass']")).shouldBe(Condition.visible).shouldHave(
        textCaseSensitive("This email is already registered",“Another Text”,“Another Text”));

More Functions:

$(“div”).scrollTo(); $(“div”).doubleClick();
$(“div”).innertText(); $(“div”).contextClick();
$(“div”).innerHtml(); $(“div”).hover();
$(“div”).exists(); $(“div”).dragAndDrop();
$(“select”).isImage(); Zoom(3.5);
$(select”).getSelectedText(); $(“select).getSelectedValue();..many more

Cross Browser Parallel Test Automation:

So far we have seen how to implement Selenide and run test on a single instance using local browser.

Problem Statement: In order to execute the same tests in multiple browsers and its multiple versions on sequential basis is tedious and mentally exhausting process. Also, it becomes infeasible to get automation test results feedback at earliest or soon. Especially, in an agile release window following CI/CD(Continuous Integration and Continuous Delivery) Integration process. In your local system , you can install a limited number of browsers,  what if you wish to use 40-50 browsers or even more with multiple browser versions?

Solution:

Selenium Grid: To address this challenge, Selenium Grid is a solution. There are option to address this problem by adding additional machines as selenium node where in our desired capabilities are utilized to pass appropriate browser version. However, maintaining a local grid could be very challenging. This is where “Cloud” solutions play a vital role.

In the below section, I’m going to setup Selenium Grid (Hub and Node) and how to run test in parallel on Chrome and Firefox browser using TestNG suite.xml

Selenium Grid Configuration  Setup:

  1. Go to seleniumhq website.
  2. Download Selenium Server latest version and store in your comfortable folder location.

019_selenium_server_download

To run Selenium Grid in Local, go to the folder location in command prompt and enter the command as mentioned below.

  • java –jar selenium-server-standalone-3.141.59.jar –role hub
    • hub indicates server where it acts as host and control your browser.

Selenium Server gets started successfully as show in the below snapshot.

020_Selenium_Grid

Now, it’s turn for Selenium Node.

Selenium Node Configuration Setup:

021_Selenium_Node

In the above snapshot, I downloaded Chrome Driver and Firefox Driver which are required to run your test in remote instance. I also created batch file to run the configuration by one click instead of each time open command prompt and enter the commands.

To create a batch file, enter the following commands. Please make sure the extension must be “.bat”

To run the batch file, navigate to specific folder in command prompt and enter “file name of your batch file” as mentioned like below snapshot.

022_Selenium_Node_start

To verify no of browser instance in Grid console, Navigate to http://localhost:4444

023_selenium_grid_Host

By default 5 Firefox, 5 Chrome and 1 IE browser exists. It’s up to your convenient number of browser instance required which can be configured in your Selenium node configuration.

Now, it’s time to run your parallel automation in cross browser platform.

Step 3 – Sample Code(Self Explanatory): Cross Browser Parallel Automation in Local

In this example, I keep it as same class in previous section but one slight modification is, I create inheritance relationship between this class and base class.

Derived Class:

package selenidesamples;

import com.codeborne.selenide.Condition;
import com.codeborne.selenide.Configuration;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;

import static com.codeborne.selenide.CollectionCondition.texts;
import static com.codeborne.selenide.Condition.text;
import static com.codeborne.selenide.Condition.textCaseSensitive;
import static com.codeborne.selenide.Selenide.*;

public class SimpleTest extends BaseConfig{

    /**
     * Author: Muthuraja R
     * Description: Validate Error message in Registration Page and capture one of error throws correct or not
     */
    @Test
    public void verifyStartTestingButton() {
        //Launch Lambdatest page
        open("https://www.lambdatest.com/");
        //use CSS Selector to find element and click for navigating register page
        $(".nav>li.login>as").click();
        //Verifying Page title using Selenide reusable method
        Assert.assertEquals("Sign up for free | Cross Browser Testing Tool | LambdaTest - LambdaTest", title());
        //Verifying text "Sign up"
        $(".signup-titel").shouldHave(text("SIGN UP"));
        //Feeding value to the text using .val
        //Feeding value to the text using sendkeys
        $(By.name("organization_name")).val("org");
        $(By.name("name")).sendKeys("Name");
        $(By.name("email")).sendKeys("test@gmail.com");
        $(By.name("password")).sendKeys("test1234");
        //using shortcut to signup instead of clicking button
        $(By.name("phone")).val("13452").pressEnter();
        //Capturing actual results and verifying with expected one using collections
        $$(".error-mass").shouldHave(
                texts("This email is already registered",
                        "Please enter a valid Phone number",
                        "To proceed further you must agree to our Terms of Service and Privacy Policy"));
    }

}

Base Class:

package selenidesamples;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;

import java.net.MalformedURLException;
import java.net.URL;

import static com.codeborne.selenide.Selenide.open;
import static com.codeborne.selenide.WebDriverRunner.setWebDriver;

public class BaseConfig {
    private WebDriver driver;
    private DesiredCapabilities desiredCapabilities;

    @BeforeClass
    @Parameters({"browserName"})
    public void init(String browserName) throws MalformedURLException {
        desiredCapabilities = new DesiredCapabilities();
        if (browserName.equals("chrome")) {
            desiredCapabilities.setCapability("browserName", "chrome");
        } else if (browserName.equals("firefox")) {
            desiredCapabilities.setCapability("browserName", "firefox");
        }
        driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), desiredCapabilities);
        setWebDriver(driver);
        open("https://www.lambdatest.com/");
        driver.manage().window().maximize();
    }

    @AfterClass
    public void tearDown() {
        if (driver != null)
            driver.quit();
    }

}

What is Desired capability?

It’s a key/value pairs that stores browser properties, platform properties etc., For eg.,It’s specific to what browser name, browser version, platform name like Windows 10, Linux etc., This will determine the behaviour of the browser during run time.

The setCapability method help to initialize and let “WebDriver” know which environment and browser to run.

The beauty of Desired Capability is, to run same test cases in different browsers with combination of its version and operating system in parallel.

In above example, I’m going to explain how I created sample test that run more than one browser.

Baseconfig class is a “Base Class” which holds Parameters,  BeforeClass and AfterClass  which are actually annotation of TESTNG. To know more details about TESTNG, please visit here but this example step by step how I designed for sample test.

Step 1: Configure TestNG XML with Thread configuration and Parameterization as below.

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Test_Suite" parallel="tests" thread-count="5">
    <test name="chrometest" >
        <parameter name="browserName" value="chrome" />
        <classes>
        <class name="selenidesamples.SimpleTest" />
    </classes>
    </test>
    <test name="firefoxtest" >
        <parameter name="browserName" value="firefox" />
        <classes>
            <class name="selenidesamples.SimpleTest" />
        </classes>
    </test>
</suite>
thread-count 5 (Mention how many thread count need)
Parameter Initialize parameter name and its value for eg., chrome or firefox
Class Include class name indicates which class you would like to execute

 

TESTNG makes your life easier in terms of running test in parallel. Configure same class under Test tag in the suites and make sure parameters added under Test for independent execution.

Step 2:

@Parameters name must be same as what as mentioned in TestNG suites.xml

025_baseConfig

While executing this code in multiple thread , two browser instances get created and run your test in parallel.4

As we already configured selenium server and it’s running. We use RemoteDriver to initialize the server host details and configure desired capabilities.

setWebDriver(driver): This method is important to initialize your customized browser configuration let WebDriverRunner in Selenide Framework otherwise it will throw timeout error and consider default browser (chrome) will execute the test in single instance.

Here is the test result in parallel execution for multiple browsers.

026_Parallel_Test_Results

Conclusion:

Selenide is a wonderful library which actually addresses many issues which was developed on top of Selenium. This library helps you to achieve your test with better reusable and better readability. The advantage of make use of this tool is, you still can write both Selenium WebDriver and Selenide code part of your framework which makes Stable and strong.

Note: I contributed same article at LambdaTest Website which can be found here

Thanks for your time, please keep us posted your feedback and comments.

Subscribe my blog for more updates!

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s