Running Selenium Automation Tests Using Selenide, IntelliJ, And Maven

Posted by Muthuraja | February 1, 2019
Automation • Cross Browser Testing • Selenium Tutorial •

21289 Views | 15 Min Read

Running Selenium Automation Tests using Selenide, IntelliJ, and Maven

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 for automated cross browser testing.

Powered by Selenium WebDriver, testing with Selenide is free as Selenide is an open source library for automation testing. 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

Testing with 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 used for Selenium testing with 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. However, when we perform Selenium testing with 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 well through Selenium testing with Selenide, 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: Selenium testing with Selenide by default, takes snapshot of failed test cases 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.

  • 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: Selenium testing with Selenide develops more focus on automation testing with better convenience in top of Selenium WebDriver.

As 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 Selenium testing with Selenide is:

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

Kick-Starting Selenium Testing With Selenide

Selenium testing with 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:

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 testing with 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.

java_image

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.

java_image

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

java_image

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.

intellijidea

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.

intellijidea

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

intellijidea

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

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

intellijidea

Add Selenide Maven Dependency as mentioned below:


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)



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.

publicclass

publicclass

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.

test@

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

string

Reusable Commands For Selenium Testing With Selenide

Here we deep dive on Selenide reusable commands:


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

elements

elements_locators

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:
elements_locators

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:

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 Selenium testing with 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.

LambdaTest – A Free Cross Browser Testing Tool: LambdaTest offers automated and live interactive cross browser testing on a Selenium grid consisting 2000+ real browsers and operating system online. LambdaTest has capability to select multiple operating systems with combination of its browser to ensure your web application runs seamlessly across different configuration. In real world, most of testing is carried out in Windows with combination of Chrome, Firefox etc. How about Linux platform with different browsers? How about MAC OS with IE browser? You can test it all using LambdaTest for browser compatibility testing.

LambdaTest also offer Cross Browser Test Automation in Parallel. We can run a single automation test on multiple browsers and their versions.

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.

standaloneserver

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.


Download Whitepaper

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


Now, it’s turn for Selenium Node.

Selenium Node Configuration Setup:


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”

java -jar selenium-server-standalone-3.141.59.jar -role node -hub
http://localhost:4444/grid/register

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.


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


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.

Selenium Testing With Selenide– 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:


Base Class:


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 <a href=”https://testng.org/doc/index.html” rel=”noopener” rel=nofollow” target=”_blank”>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

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
Doctype

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.
Doctype

Running Parallel Test In LambdaTest For Selenium Testing With Selenide

To execute same test in Parallel on LambdaTest is very simple and straightforward. I’m going to explain same scripts in LambdaTest except few tweak in the code on BaseConfig class & TestNG.
Doctype

In this example, I added few more parameters to run the same script in LambdaTest

Browser Name Customized way to configure your browser name like Chrome, Firefox etc
Platform LambdaTest offers to run in different platform Windows 10, Linux etc.,
Browser Version LambdaTest offers you to select different browser version which actually help you to validate your test like how your product is being used by customers
Visual Enable This feature is basically to record all execution in videos and logs.

You still can add customized configuration, please visit here.
capabilitygenerator

Changes In BaseConfig Class For LambdaTest

capabilitygenerator

In the above code, I use two method which are:

  • getLambdaUserName()
  • getLambdaPassword()

These methods will actually get LambdaTest User account and password from environment variable which you set in the machine.

How To Set Environment Variable For LambdaTest Username/Password?

In Windows 10 -> Search Environment Variable -> Edit the System Environment Variable -> Click New button

  • Enter variable name as “LAMBDA_USERNAME”
  • Enter variable value as “YOUR_LAMBDA_ACCOUNT”

capabilitygenerator

Note:

  • Similarly do the same for Password
  • API key can be generated in your profile page in LambdaTest Login
  • Click “Ok” button
    To Run Parallel:

  • Open “testsuites_Parallel_Lambda.xml”.
  • Right click on the xml and click Run in Intellij.

capabilitygenerator

Test results run in LambdaTest portal and the result can be displayed in the below snapshot.
capabilitygenerator

Navigated to specific test for detail view, where you can see the following parameter of the screen.

  • Summary
  • Exception
  • Command
  • Network
  • Logs
  • Metadata

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.
Thanks for your time, please keep us posted your feedbacks and comments.

Written by Muthuraja R

Muthuraja R is an Automation Architect with 12+ years of experience in Test Automation, Performance, Security and Manual Testing. He is TDD BDD Enthusiast, Blogger, Technical Writer, Full Stack QA Engineer and Technology Evangelist and has a technical blog named as https://automationcalling.com/ where he provides solution, ideas sharing, techniques, framework development and address problems to all the challenges offered in the day to day activities, he can be followed up at: https://www.linkedin.com/in/muthuraja-r-b0786a25/

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *