How to Perform Selenium Automation Using LambdaTest?

Automation testing has become a basic need for organizations that run their business online. It is a testing technique that is used to ensure that a web application works fine across all browsers, operating system, and devices in terms of functionality, speed, and accuracy. There are multiple testing platforms and tools that can be used for automation testing like Robotium, TestComplete, SoapUI, Ranorex, and many more.

But, there is no match for Selenium. It is the most recommended tool for automation testing by large as well as small organizations. So, if you’re starting out with automation testing and don’t know what selenium is and how it is beneficial for automation testing?

Then don’t worry! We’re here to help.

In this article, we will discuss every aspect of selenium automation and how LambdaTest Selenium Grid can be used to perform selenium automation.

What is Selenium?

Selenium is an automated testing tool that is specially designed to automate web application testing. With Selenium automation, test scripts automatically perform the same interaction over different browsers for a web application so that testers don’t have to perform it manually.

In usual terms, it is known as Selenium Suite because it is not an individual tool. Selenium is a collection of four major tools , which include:

  • Selenium Integrated Development Environment(IDE)
  • Selenium Remote Control
  • Selenium WebDriver
  • Selenium Grid

These four tools make selenium suite the most used and recommended tool for automation testing. Selenium can be used to perform any type of automated testing, but it is primarily used for automated cross browser testing. Apart from that, it is an open-source tool, so there is no licensing cost involved, which is a huge advantage over other automation testing tools.

Now, let’s have a look at the other advantages that selenium has to offer for automation testing.

Benefits of Selenium Automation

The benefits of Selenium automation are endless. However, there are some unique benefits that make it the first choice of organizations for website testing. Let’s have a look at these benefits:

Open-source

As mentioned earlier, Selenium is an open-source automated testing framework, which makes it a freeware and portable testing tool. Also, being an open-source framework, it doesn’t involve any licensing cost, which is a significant advantage over other tools.

Uses Common Script for Cross Browser Testing

With Selenium, you can perform cross browser testing across Chrome, Firefox, Safari, Internet Explorer, and Opera with only one test script on almost every platform like Windows, Linux, and Mac, . Customers use different devices and platform to access the internet; selenium allows testers to improve their test coverage with just one test script over all the devices and platforms.

Earlier Detection of Defects

As a tester, you might know the importance of early defect detection which leads to cost-effective code rework. Selenium not only detects defects earlier, but It also helps in maintaining the overall velocity of code development while ensuring that the functionality of the website is not compromised.

Testing Efficiency Improvement

Usually, automation testing takes less time to set up as compared to manual testing. But, selenium automation is even faster than other automation testing techniques. The time required to set up the selenium framework is much less than other tools, which make it the most efficient tool for website testing.

Multiple Language Support

One of the biggest challenges in automation testing is the incorporation of automation tools with the development environment for CI. Selenium support multiple programming languages like Java, Python, Perl, C#, Ruby, JavaScript, and many more, which makes it is easy to integrate with the development environment. Although it has its own script, it doesn’t limit to that specific language. Testers and developers can use it with any language that they are comfortable with.

Easy to Implement

The user-friendly interface of selenium makes it easy for the testers and developers to execute tests across various platforms. The open-source features allow testers to write the script with their own extensions so that it becomes easy to develop customized actions. Also, the reporting capability of selenium is one of the main reasons to choose it because it helps testers extract test results and take necessary action.

It’s not a Utility; It’s a Suite

As mentioned earlier, selenium is not a single utility. It is a package of multiple testing tools, and that’s why it is referred to a suite. Each of the selenium testing tools is designed for different testing requirements. For instance, selenium has the capability to support Selenium IDE, Selenium Grid, Selenium WebDriver, and Selenium Remote Control.

Integrates Easily with Testing Tools

Selenium has its own set of standards which allow it to use with popular software development and testing tools easily. For example, it easily integrates SC compilers, such as Maven and ANT, cloud-grids like LambdaTest, CI systems like TeamCity and Jenkins, and many other test management tools.

These benefits clearly prove why selenium is the best automation testing tool. After knowing these benefits, you definitely wanted to see how you can perform selenium automation with multiple languages for your web application.

We have got you covered for that too!

To perform selenium automation, you need a grid  that allows you to test web application with different programming languages across various browsers and devices. And LambdaTest proved to be a genuine and quality online selenium grid for performing cross browser testing as well as other web application testing.

Performing Selenium Automation with LambdaTest Selenium Grid

If you are looking for a reliable platform to perform selenium automation testing, then LambdaTest can be your end of research. LambdaTest is recognized as one of the best platforms for Selenium automation testing. The selenium automation Grid from LambdaTest allows users to perform end-to-end automation tests on a reliable, secure, and scalable selenium infrastructure.

With LambdaTest Selenium Grid, you can perform automated cross browser testing across more than 2000 browsers and operating systems, which gives you higher test coverage. It helps you analyze how your web application renders across different browsers. Also, using Lambda Tunnel, you can perform automated cross browser testing of your locally hosted web pages. In addition, it supports all the languages and frameworks that are compatible with selenium automation like Java, PHP, Python, C#, Ruby, and JavaScript.

Here we will discuss how LambdaTest can be used for selenium automation with different programming languages and frameworks. But, before that, it’s necessary to understand the capabilities of the LambdaTest Selenium Automation Grid.

Understanding the Capabilities of the LambdaTest Selenium Grid

LambdaTest Selenium Grid uses remote Webdriver instead of normal Selenium client browser drivers.  So, if you want to migrate from locally run Selenium, then you will have to invoke LambdaTest Selenium remote WebDriver.

After that, you’ll have to specify in the code about the browser, browser versions, operating systems, and resolution that you want to run your test on, along with defining LambdaTest specific capabilities. You can check out the LambdaTest Capability Generator tool to know more about how you can define running browser environments and leverage advanced LambdaTest capabilities.

Now, let’s get back to perform selenium automation with different programming languages.

Getting Started with LambdaTest Selenium Grid

1) Java on LambdaTest Selenium Grid

To better understand LambdaTest Selenium Grid automation with Java, let’s take an example of Selenium Remote Webdriver test. Below is a program of Java code that tests a simple to-do application with normal functionalities, such as mark items as done, add items in the list, calculate total pending items, etc.

Java To-Do: Sample App

import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class JavaTodo {
 String username = “YOUR_USERNAME”;
 String accesskey = “YOUR_ACCESS_KEY”;
 static RemoteWebDriver driver = null;
 String gridURL = “@hub.lambdatest.com / wd / hub”;
 boolean status = false;
 public static void main(String[] args) {
  new JavaTodo().test();
 }
 public void test() {
   // To Setup driver
   setUp();
   try {
    //Change it to production page
    driver.get(“https: //lambdatest.github.io/sample-todo-app/”);
      //Let's mark done first two items in the list.
      driver.findElement(By.name(“li1”)).click(); driver.findElement(By.name(“li2”)).click();
      // Let's add an item in the list.
      driver.findElement(By.id(“sampletodotext”)).sendKeys(“Yey, Let 's add it to list”);
       driver.findElement(By.id(“addbutton”)).click();
       // Let's check that the item we added is added in the list.
       String enteredText = driver.findElementByXPath(“/html/body / div / div / div / ul / li[6] / span”).getText();
       if (enteredText.equals(“Yey, Let 's add it to list”)) {
         status = true;
        }
       }
       catch (Exception e) {
        System.out.println(e.getMessage());
       } finally {
        tearDown();
       }
      }
      private void setUp() {
       DesiredCapabilities capabilities = new DesiredCapabilities();
       capabilities.setCapability(“browserName”, “chrome”);
       capabilities.setCapability(“version”, “70.0”);
       capabilities.setCapability(“platform”, “win10”); // If this cap isn't specified, it will just get any available one.
       capabilities.setCapability(“build”, “LambdaTestSampleApp”);
       capabilities.setCapability(“name”, “LambdaTestJavaSample”);
       capabilities.setCapability(“network”, true); // To enable network logs
       capabilities.setCapability(“visual”, true); // To enable step by step screenshot
       capabilities.setCapability(“video”, true); // To enable video recording
       capabilities.setCapability(“console”, true); // To capture console logs
       try {
        driver = new RemoteWebDriver(new URL(“https: //” + username + “:” + accesskey + gridURL), capabilities);
         }
         catch (MalformedURLException e) {
          System.out.println(“Invalid grid URL”);
         } catch (Exception e) {
          System.out.println(e.getMessage());
         }
        }
        private void tearDown() {
         if (driver != null) {
          ((JavascriptExecutor) driver).executeScript(“lambda - status = “+status);
          driver.quit(); //really important statement for preventing your test execution from a timeout.
         }
        }
       }

On running this test, a URL will be opened by Selenium Webdriver, mark the first two items as done in the list, add an item to the list, and return the total number of pending items. The test results will be displayed on the test console (or command-line interface if you are using terminal/cmd) and LambdaTest dashboard. LambdaTest Dashboard helps testers to view their text logs, screenshots and video recording for the entire Selenium tests.

Executing the Test

To execute the test, you need to run the below command in terminal/cmd.

  1. cd to/file/location
  2. compile the test file: javac -classpath “.:/path/to/selenium/jarfile:” JavaTodo.java
  3. Run the test:  java -classpath “.:/path/to/selenium/jarfile:” JavaTodo

Example:

  1. cd /home/admin1/eclipseworkspace/Demo
  2. javac -classpath “.:/home/admin1/eclipseworkspace/Demo/src/selenium-server-standalone-3.14.0.jar:” JavaTodo.java
  3. java -classpath “.:/home/admin1/eclipseworkspace/Demo/src/selenium-server-standalone-3.14.0.jar:” JavaTodo

Configuring Capabilities of Java for Selenium Automation

To connect with LambdaTest Selenium automation gird, first, you’ll have to configure your test scripts. In the above Java code, the first thing you might have noticed is the invoking of remote WebDriver instead of the native browser Webdrivers. So, if you want to run this test with Firefox browser on your local machine, you will have to use Firefox browser driver like this:

  • Local Driver
FirefoxDriver driver = new FirefoxDriver();

But, to run LambdaTest Selenium Grid, you’ll have to change it to remote WebDriver, and at the same time pass capabilities related to the browser, browser versions, etc. Then it will look something like this:

  • Remote Web Driver
WebDriver driver = new RemoteWebDriver(new URL(“https://” + username + “:” + accesskey + gridURL), capabilities);

In the above code, we passed browser, browser version, and operating system information, along with LambdaTest Selenium grid capabilities via capabilities object. The capabilities object in the above code can be defined as:

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(“browserName”, “chrome”);
capabilities.setCapability(“version”, “70.0”); 
capabilities.setCapability(“platform”, “win10”); // If this cap isn't specified, it will just get the any available one
capabilities.setCapability(“build”, “LambdaTestSampleApp”);
capabilities.setCapability(“name”, “LambdaTestJavaSample”);
capabilities.setCapability(“network”, true); // To enable network logs
capabilities.setCapability(“visual”, true); // To enable step by step screenshot
capabilities.setCapability(“video”, true); // To enable video recording
capabilities.setCapability(“console”, true); // To capture console logs

Here the most important capabilities are ‘browserName’, ‘version’, and ‘platform’. These capabilities define which browser environment you want to run the test on. The remaining capabilities are important in test management and debugging.

Frameworks for Java Selenium Automation

Now, if you want to use the Lambdatest Selenium Automation Grid with a Java-based framework, then there are two testing frameworks available – JUnit and TestNG.

  • JUnit – It is an open-source testing framework for Java which is specially designed for Java developers to write and run repeatable tests. However, it can only be used for Unit Testing of a small portion of code.
  • TestNG – It is another open-source automated testing framework for Java along with JUnit. However, it has some advanced functionalities which make it more powerful and easy to use. For example, with TestNG, you can easily create a proper report and get to know how many test cases failed, passed, or skipped.

Both JUnit and TestNG frameworks have similar capabilities to Java and are supported on LambdaTest platform.

2) C# on LambdaTest Selenium Grid

C# is an object-oriented programming language that is derived from C++ and Java. It allows developers to build web applications using Visual Studio on .Net platform. You can bind C# with selenium automation easily. To understand LambdaTest Selenium automation with C# language, let’s take an example of a simple Selenium Remote WebDriver test case. We will test a simple to-do application with the C# script mentioned below with basic functionalities, such as mark items as done, add items in the list, calculate total pending items, etc.

C# To-do: Sample App

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using System;
using System.Configuration;
namespace LambdaTestCSharp {
 public class Program {
  private static IWebDriver driver;
  private static String ltUserName;
  private static String ltAppKey;
  private static String platform;
  private static String browser;
  private static String browserVersion;
  static void Main(string[] args) {
   InitCaps();
   DesiredCapabilities caps1 = new DesiredCapabilities();
   caps1.SetCapability(“platform”, platform);
   caps1.SetCapability(“browserName”, browser); // name of your browser
   caps1.SetCapability(“version”, browserVersion); // version of your selected browser
   caps1.SetCapability(“name”, “CSharpTestSample”);
   caps1.SetCapability(“build”, “LambdaTestSampleApp”);
   caps1.SetCapability(“user”, ltUserName);
   caps1.SetCapability(“accessKey”, ltAppKey);
   caps1.SetCapability(“network”, true); // To enable network logs
   caps1.SetCapability(“visual”, true); // To enable step by step screenshot
   caps1.SetCapability(“video”, true); // To enable video recording
   caps1.SetCapability(“console”, true); // To capture console logs
   Console.WriteLine(ConfigurationSettings.AppSettings[“LTUrl”]);
   driver = new RemoteWebDriver(new Uri(ConfigurationSettings.AppSettings[“LTUrl”]), caps1, TimeSpan.FromSeconds(600));
   driver.Manage().Window.Maximize();
   driver.Url = “https: //lambdatest.github.io/sample-todo-app/“;
    Assert.AreEqual(“Sample page - lambdatest.com”, driver.Title)
   String itemName = “Yey, Let 's add it to list”;
   // Click on First Check box 
   IWebElement firstCheckBox = driver.FindElement(By.Name(“li1”));
   firstCheckBox.Click();
   // Click on Second Check box 
   IWebElement secondCheckBox = driver.FindElement(By.Name(“li2”));
   secondCheckBox.Click();
   // Enter Item name  
   IWebElement textfield = driver.FindElement(By.Id(“sampletodotext”));
   textfield.SendKeys(itemName);
   // Click on Add button 
   IWebElement addButton = driver.FindElement(By.Id(“addbutton”));
   addButton.Click();
   // Verified Added Item name
   IWebElement itemtext = driver.FindElement(By.XPath(“/html/body / div / div / div / ul / li[6] / span”));
   String getText = itemtext.Text;
   Assert.IsTrue(itemName.Contains(getText));
   driver.quit(); //really important statement for preventing your test execution from a timeout.
  }
  public static void InitCaps() {
   If(String.IsNullOrEmpty(Environment.GetEnvironmentVariable(“LT_USERNAME”))) {
    ltUserName = ConfigurationSettings.AppSettings[“LTUser”];
   }
   If(String.IsNullOrEmpty(Environment.GetEnvironmentVariable(“LT_APPKEY”)) ltAppKey = ConfigurationSettings.AppSettings[“LTAccessKey”];
    if (String.IsNullOrEmpty(Environment.GetEnvironmentVariable(“LT_OPERATING_SYSTEM”)))
     platform = ConfigurationSettings.AppSettings[“OS”];
    if (String.IsNullOrEmpty(Environment.GetEnvironmentVariable(“LT_BROWSER”)))
     browser = ConfigurationSettings.AppSettings[“Browser”];
    if (String.IsNullOrEmpty(Environment.GetEnvironmentVariable(“LT_BROWSER_VERSION”)))
     browserVersion = ConfigurationSettings.AppSettings[“BrowserVersion”];
   }
  }
 }

Below is the App.config file that will be used to set application settings in C#.

<?xml version=“1.0” encoding=“utf-8” ?>
<configuration>
	<startup>
		<supportedRuntime version=“v4.0” sku=“.NETFramework,Version=v4.5.2” />
	</startup>
	<appSettings>
		<add key=“URL” value=“https://lambdatest.github.io/sample-todo-app/“ />
		<add key=“LTUser” value= ““>
		<add key=“LTAccessKey” value=““ />
		<add key=“LTUrl” value=“https://hub.lambdatest.com/wd/hub“ />
		<add key=“Browser” value=“chrome” />
		<add key=“BrowserVersion” value=“62.0” />
		<add key=“OS” value=“win10” />
	</appSettings>
</configuration>

This Selenium Webdriver test will open a URL on the screen. In the opened URL, mark the first two items as done in the list, add an item in the list, and return the total number of pending items. The test results will be displayed on the test console (or command-line interface if you are using terminal/cmd) and on LambdaTest dashboard. LambdaTest Dashboard allows users to view all their screenshots, text logs, and video recording for the entire Selenium test.

Execute the Test

Use the below command in your terminal/cmd to execute the C# test.

  1. Command Required

Configuring C# Capabilities for Selenium Automation

As mentioned earlier, you’ll have to configure test script for every language that you’re using to connect with LambdaTest Selenium Automation Grid. In the above C# code, the first thing you will notice is the invoking of remote WebDriver instead of the native browser Webdrivers. So, if you want to run this test with Firefox browser on your local computer, then you will have to use Firefox browser driver like this:

  • Local Driver
bDriver driver = new FirefoxDriver();

But, with LambdaTest Selenium Grid, you’ll have to change the local driver to remote WebDriver, and pass capabilities related to the browser, browser versions, etc. at the same time. Then it will look something like this:

  • Remote WebDriver
IWebDriver driver= new RemoteWebDriver(new URL(https://hub.lambdatest.com/wd/hub), caps1, TimeSpan.FromSeconds(600));

In the above C# code, we passed browser, browser version, and operating system information, along with LambdaTest Selenium grid capabilities via capabilities object. The capability generator from LambdaTest will automatically generate the program based on the input. The capabilities object in the above C# code can be defined as:

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability(“build”, “your build name”);
capabilities.SetCapability(“name”, “your test name”);
capabilities.SetCapability(“platform”, “macOS High Sierra”); // Selected Operating system
capabilities.SetCapability(“browserName”, “Firefox”); // Name of your selected browser.
capabilities.SetCapability(“version”,”64.0”); // Selected Browser Version
capabilities.SetCapability(“resolution”,”1280x1024”); // Screen resolution of your VM(Virtual Machine).
capabilities.SetCapability(“selenium_version”,”3.13.0”); // Selenium version
capabilities.SetCapability(“visual”,true);
capabilities.SetCapability(“firefox.driver”,v0.23.0);

The most important capabilities for C# are ‘browserName’, ‘version’, and ‘platform’. These capabilities define which browser environment you want to run the test on. The remaining capabilities are important in test management and debugging.

Frameworks for C# Selenium Automation

To use the Lambdatest Selenium Automation Grid with a C# based framework, there are three testing frameworks available – NUnit, MSTest, and SpecFlow.

  • NUnit – It is a testing framework for unit-testing for all the .NET languages. It is absolutely free to use and doesn’t create any test script by itself. It allows testers to use custom attribute and other reflection related capabilities.
  • MSTest – It is a command line tool that is used for unit testing of.NET applications. It can easily be integrated with TestComplete to test your test projects and run them as a part of the automated testing process.
  • SpecFlow – It is a behavior-driven development testing framework. SpecFlow tests define how an application should behave in different scenarios. The tests in SpecFlow are written in plain English so that developers, marketers, testers, and everyone else involved in the application testing can easily understand the codes.

All three frameworks have similar capabilities to C# and are available on LambdaTest platform.

3) JavaScript on LambdaTest Selenium Grid

JavaScript is a preferred programming language that is used to interact with HTML dom inside the browser. Most back-end developers prefer JavaScript than any other language for web application development. JavaScript frameworks provide both safety and efficiency at no cost, as it is an open-source framework. To understand LambdaTest Selenium Grid automation with JavaScript, let’s take an example of a simple Selenium Remote WebDriver test case.

Spec.js

// spec.js
describe('Add todo Lists', function() {
   browser.ignoreSynchronization = true;
   it('Add Customer Test', function() {
    browser.get('https://lambdatest.github.io/sample-todo-app/');
    browser.driver.findElement(by.name('li1')).then(function(foundElement) {
     foundElement.click();
    });

    browser.driver.findElement(by.name('li2')).then(function(foundElement) {
     foundElement.click();
    });

    browser.driver.findElement(by.id('sampletodotext')).then(function(foundElement) {
      foundElement.clear();
      foundElement.sendKeys(“Yey, Let 's add it to list”);
      }); browser.driver.findElement(by.id('addbutton')).then(function(foundElement) {
      foundElement.click();
     });

     var foo = element(by.xpath('//html/body/div/div/div/ul/li[6]/span')); expect(foo.getText()).toEqual(“Yey, Let 's add it to list”);
      browser.executeScript(“lambda - status = passed”); browser.driver.quit();
     });
   });

The config.js mentioned below will declare the desired capabilities of the test.

Export.config

exports.config = {

// change this to your USERNAME and ACCESSKEY
seleniumAddress: 'https://USERNAME:ACCESSKEY@hub.lambdatest.com/wd/hub',
capabilities: [{
'name': 'Single Test ',
'build': 'JavaScript Example',
'browserName': 'Chrome',      //Selected browser name 
'platform': 'WIN10',        //Selected OS name
'version':'69.0',            // Selected browser version
'video': true,  //To Enable video recording 
'visual': true, //To Enable step by step screenshot
'network': true,    //To capture Network logs      
'console': true   //To capture Console Logs    
}],
specs: './tests/*.js'
};

In the opened URL, the test script will mark the first two items as done in the list, add an item in the list, and return the total number of pending items. The test results will be displayed on the test console (or command-line interface if you are using terminal/cmd) and on LambdaTest dashboard.

Execute the Test

Use the below command in your terminal/cmd to execute the test.

node config.js

Configuring JavaScript Capabilities for Selenium Automation

  • Local Browser Code
//In Conf.js
exports.config = {
seleniumAddress: 'https://localhost:4445/wd/hub',

// add more browsers to this array for more parallel tests!!
multiCapabilities: [{
'browserName': 'firefox',     
'platform': 'WIN10',        
'version':'62.0',

}],

//Add test scripts in this array to execute in parallel
specs: ['tests/spec.js']
};

But, with LambdaTest Firefox browser, the code will be changed to below command:

  • Remote Web Driver
seleniumAddress: 'https://USERNAME:ACCESSKEY@hub.lambdatest.com/wd/hub'

The same information as Java and C# will be passed through JavaScript code along with LambdaTest Selenium grid capabilities.

Browser/OS Capabilities

var capabilities = {“
 build”: “your build name”, //You can edit this and assign a build name
 “name”: “your test name”, // Assign a name to your Test
 “platform”: “Windows 8.1”, // The operating system on which you want to test your website
 “browserName”: “Firefox”, // The browser on which you want to test
 “version”: “62.0”, // The browser version which you've selected to perform the test upon
 “resolution”: “1280 x1024”, // The resolution in which you want to run the test as per your operating system
 “selenium_version”: “3.11 .0”, //The version of Selenium on which the test will run
 “visual”: true,
 “firefox.driver”: v0 .21 .0
}

The most important capabilities for JavaScript are ‘browserName’, ‘version’, and ‘platform’.

Frameworks for JavaScript Selenium Automation

To use Lambdatest Selenium Automation Grid with JavaScript based framework, there are four testing frameworks available – Protractor, Nightwatch, WD, and WebDriverIO.

  • Protractor – It is an end-to-end framework for application testing developed in the AngularJS language. It works as a solution integrator to combine powerful technologies, such as Jasmine, WebDriver, and Selenium. You can also use it to write automated regression tests for normal web applications.
  • Nightwatch – It is also an integrated end-to-end testing framework based on Node.js and Selenium WebDriver, and uses W3C WebDriver API for performing assertions on DOM elements. It has a simple yet powerful syntax that allows you to write tests quickly using JavaScript and CSS or XPath.
  • WD.js – It is a Node.js client that is used with WebDriver/Selenium for JavaScript web application testing. WD libraries are designed to check the code is behaving properly in all browsers.
  • WebDriverIO – It is a next-gen testing framework for Node.js applications. The command line interface of WDIO comes with a simple configuration utility that allows you to create your config file within seconds.

The capabilities for all these frameworks are similar to JavaScript.

4) PHP on LambdaTest Selenium Grid

PHP is a universally used and one of the faster open-source server-side scripting languages that are used for large scale web applications, such as Facebook, WordPress, etc. It can be embedded into HTML code easily. To run selenium automation testing and PHP, you’ll have to set up PHP for your OS. If you’re performing tests on Windows OS, then enable the PHP curl library and Open SSL support for better performance. Once all the prerequisites to run PHP with selenium are installed, you can run LambdaTest.php test to ensure that everything works.

Now, to understand LambdaTest Selenium automation with PHP, let’s take a look at the below example that will validate the LambdaTest credentials for authentication purpose.

<?php
require 'vendor/autoload.php';
$GLOBALS['LT_USERNAME'] = getenv('LT_USERNAME');
if(!$GLOBALS['LT_USERNAME']) $GLOBALS['LT_USERNAME'] = “************************************”;
$GLOBALS['LT_APPKEY'] = getenv('LT_APPKEY');
if(!$GLOBALS['LT_APPKEY']) $GLOBALS['LT_APPKEY'] = “*****************************************”;
$GLOBALS['LT_BROWSER'] = getenv('LT_BROWSER');
if(!$GLOBALS['LT_BROWSER']) $GLOBALS['LT_BROWSER'] = “chrome”;
$GLOBALS['LT_BROWSER_VERSION'] = getenv('LT_BROWSER_VERSION');
if(!$GLOBALS['LT_BROWSER_VERSION']) $GLOBALS['LT_BROWSER_VERSION'] =“63.0”;
$GLOBALS['LT_OPERATING_SYSTEM'] = getenv('LT_OPERATING_SYSTEM');
if(!$GLOBALS['LT_OPERATING_SYSTEM']) $GLOBALS['LT_OPERATING_SYSTEM'] = “win10”;
class LambdaTest{
protected static $driver;
public function testAdd() {             
$url = “https://”. $GLOBALS['LT_USERNAME'] .”:” . $GLOBALS['LT_APPKEY'] .”@hub.lambdatest.com/wd/hub”;      
$desired_capabilities = new DesiredCapabilities();
$desired_capabilities->setCapability('browserName',$GLOBALS['LT_BROWSER']);
$desired_capabilities->setCapability('version', $GLOBALS['LT_BROWSER_VERSION']);
$desired_capabilities->setCapability('platform', $GLOBALS['LT_OPERATING_SYSTEM']);
$desired_capabilities->setCapability('name', “PHPTestSample”);
$desired_capabilities->setCapability('build', “LambdaTestSampleApp”);
$desired_capabilities->setCapability('network', true);
$desired_capabilities->setCapability('visual', true);
$desired_capabilities->setCapability('video ', true);
$desired_capabilities->setCapability('console', true);
self::$driver = RemoteWebDriver::create($url, $desired_capabilities);
$itemName = 'Yey, Lets add it to list';
self::$driver->get(“https://lambdatest.github.io/sample-todo-app/“);
$element1 = self::$driver->findElement(WebDriverBy::name(“li1”));
$element1->click();
$element2 = self::$driver->findElement(WebDriverBy::name(“li2”));
$element2->click();
$element3 = self::$driver->findElement(WebDriverBy::id(“sampletodotext”));
$element3->sendKeys($itemName);
$element4 = self::$driver->findElement(WebDriverBy::id(“addbutton”));            
$element4->click();
self::$driver->wait(10, 500)->until(function($driver) {
$elements = $driver->findElements(WebDriverBy::cssSelector(“[class='list-unstyled'] li:nth-child(6) span”));
return count($elements) > 0;
});
self::$driver->quit();
}
}
$lambdaTest = new LambdaTest();
$lambdaTest->testAdd();
?>

Executing the Test

Use the below command in your terminal/cmd to execute the test case.

php tests\LambdaTest.php

Configuring PHP Capabilities for Selenium Automation

  • Local Browser Code

To run the code on Firefox browser hosted by LambdaTest, you’ll have to add the following command:

FirefoxDriver driver = new FirefoxDriver();

But, with LambdaTest Firefox browser, the code will be changed to below command.

  • Remote Web Driver
self::$driver = RemoteWebDriver::create(“https://Username:Accesskey@hub.lambdatest.com/wd/hub”, $desired_capabilities);

The same information as Java, C#, and JavaScript will be passed through PHP code along with LambdaTest Selenium grid capabilities.

Browser/OS Capabilities

$capabilities = array(
“build” => “your build name”,
“name” => “your test name”,
“platform” => “macOS High Sierra”,
“browserName” => “Firefox”,
“version” => “64.0”,
“resolution” => “1280x1024”,
“selenium_version” => “3.13.0”,
“screenshot” => true,
“firefox.driver” => v0.23.0
)

The most important capabilities for PHP are ‘browserName,’ ‘version,’ and ‘platform.’

Frameworks for PHP Selenium Automation

To use Lambdatest Selenium Automation Grid with PHP based framework, there are three testing frameworks available – Behat, Laravel Dusk, and PHPUnit.

  • Behat – It is an open-source behavior-driven development testing framework for PHP. The codebase in Behat uses Symfony components, religiously follows coding standards, and have high ratings in major static analysis tools. The framework functionality can easily be replaced with the powerful extension system of Behat.
  • Laravel Dusk – It was introduced by Laravel 5.4 to test JavaScript-based application functionality that was not possible with PHPUnit. It is based on ChromeDriver and Facebook Php web driver, which makes it easy to use even without experiencing the intense procedure of setting up selenium.
  • PHPUnit – It is a part of xUnit architecture that originated with SUnit and becomes popular with JUnit. It is a programmer-oriented testing framework used for unit testing of web applications with PHP language.

All three frameworks have similar capabilities to PHP.

5) Python on LambdaTest Selenium Grid

Python is an object-oriented and interpreted high-level programming language with dynamic semantics. The simple and easy-to-learn syntax of Python emphasizes readability while reducing the cost of program maintenance. It can easily be utilized with Selenium for automation testing. The Python APIs allows you to connect with browsers through Selenium quickly. To understand LambdaTest Selenium Grid automation with Python, let’s take an example of a simple Selenium Remote WebDriver test case.

import unittest, time, re
import base_test

from selenium.webdriver.common.keys import Keys

class LambdaTest(base_test.BaseTest):

def test_unit_user_should_able_to_add_item(self):

# try:

driver = self.driver

# Url

driver.get(self.base_url)

# Click on check box

check_box_one = driver.find_element_by_name(“li1”)

check_box_one.click()

# Click on check box

check_box_two = driver.find_element_by_name(“li2”)

check_box_two.click()

# Enter item in textfield

textfield = driver.find_element_by_id(“sampletodotext”)

textfield.send_keys(“Yey, Let's add it to list”)

# Click on add button

add_button = driver.find_element_by_id(“addbutton”)

add_button.click()

# Verified added item

added_item = driver.find_element_by_xpath(“//span[@class='done-false']”).text

print (added_item)

self.assertEqual (“Yey, Let's add it to list”, added_item )

if added_item in “:

return True

else:

return False

if __name__ == “__main__”:

unittest.main()

Executing the Test

Use the below command in your terminal/cmd to execute the test case.

python lambdatest_test.py

Configuring Python Capabilities for Selenium Automation

  • Local Driver

To run the code on Firefox browser hosted by LambdaTest, you’ll have to add the following command:

 FirefoxDriver driver = new FirefoxDriver();

But, to run on LambdaTest Selenium Grid, the code will be changed to below command.

  • Remote Web Driver
self.driver = webdriver.Remote(command_executor=“https://USERNAME:ACCESSKEY@hub.lambdatest.com/wd/hub”,desired_capabilities=caps)

Information about the browser, browser version, and operating system, along with LambdaTest Selenium grid capabilities via capabilities object will be passed in the above Code.

For example, if you want to define the capabilities for invoking a specific Remote web chrome driver, then use the following command:

Remote Web Driver Capability

capabilities = {
“chrome.driver” : 2.42
}

Browser/OS Test Configuration for Python

capabilities = {
“build” : “your build name”,
“name” : “your test name”,
“platform” : “Windows 10”,
“browserName” : “Chrome”,
“version” : “71.0”
}

The most important capabilities for Python are ‘browserName,’ ‘version,’ and ‘platform.’

Frameworks for Python Selenium Automation

To use the Lambdatest Selenium Automation Grid with a Python-based framework, there is one testing framework available – Behave.

  • Behave – As the name defines, it is a behavior-driven testing framework that is used for behavior testing of a web application. It enhances collaboration between developers, testers, and other participants involved in a development project. It focuses on obtaining a clear understanding of desired software behavior and makes it easy to turn the scenario into automated tests.

It has similar capabilities to Python.

6) Ruby on LambdaTest Selenium Grid

Ruby is a vibrant and open-source programming language that focuses on easiness and efficiency. It provides great flexibility to solve problems related to a web application using different methods. To run ruby with selenium, you’ll have to install both Ruby and gem on your local computer. Both these platforms are different for each operating system.

For Linux and Ubuntu OS, you can install Ruby using the below command:

$ sudo apt-get install ruby-full

For MacOS, you can install Ruby by running a homebrew command like this:

$ brew install ruby

Also, for parallel testing of a web application, you’ll need the parallel_tests gem. Once you set up Ruby and gem on your local system, you’ll have to install Selenium dependencies. You can use the below command to install selenium dependencies:

gem install selenium-webdriver

Now, to understand the LambdaTest Selenium Automation Grid with Ruby, let’s take a look at the below code that will validate if there are any changes in the title of Google’s home page.

LambdaTest.rb


require 'rubygems'
require 'selenium-webdriver'
require 'test/unit'
require_relative  “readConf”
class AdvanceTest < Test::Unit::TestCase
def setup
config = ReadConfig.new()   
lt_user = ENV['LT_USERNAME']
lt_appkey = ENV['LT_APPKEY']
lt_os = ENV['LT_OPERATING_SYSTEM']
lt_browser = ENV['LT_BROWSER']
lt_browser_version = ENV['LT_BROWSER_VERSION']
if(lt_user == ““ || lt_user == nil)
lt_user = config.getDetails('LT_USERNAME')
end
if(lt_appkey == ““ || lt_appkey == nil)
lt_appkey = config.getDetails('LT_APPKEY')
end

if(lt_browser == ““ || lt_browser == nil)
lt_browser = config.getDetails('LT_BROWSER')
end

if(lt_os == ““ || lt_os ==nil)
lt_os = config.getDetails('LT_OPERATING_SYSTEM')
end

if(lt_browser_version == ““ || lt_browser_version == nil)
lt_browser_version = config.getDetails('LT_BROWSER_VERSION')
end

caps = {                        
:browserName => lt_browser,          
:version => lt_browser_version,          
:platform =>  lt_os,
:name =>  “RubyRSpecTestSample”,
:build =>  “LambdaTestSampleApp”,       
:network =>  true,
:visual =>  true,
:video =>  true,
:console =>  true
}   

puts (caps)
@driver = Selenium::WebDriver.for(:remote,:url => “https://”+lt_user+”:”+lt_appkey+”@hub.lambdatest.com/wd/hub”, :desired_capabilities => caps)

@driver.manage.window.maximize

@driver.get(“https://lambdatest.github.io/sample-todo-app/” )

end

def test_Login

item_name = “Yey, Lets add it to list”

#Click on First Checkbox
fCheckbox = @driver.find_element(:name, 'li1')

fCheckbox.submit

#Click on Second Checkbox
sCheckbox = @driver.find_element(:name, 'li2')
sCheckbox.submit
#Enter Item Name 
itemNameInput = @driver.find_element(:id, 'sampletodotext')
itemNameInput.send_keys item_name

#Click on Add Button
addButton = @driver.find_element(:id, 'addbutton')

addButton.submit

# Verify Added Item
getItemName = @driver.find_element(:xpath, '/html/body/div/div/div/ul/li[6]/span').text

assert_equal(getItemName, item_name )

end

def teardown

@driver.quit

end

end

This Selenium Webdriver test will open a URL on the screen. In the opened URL, mark the first two items as done in the list, add an item in the list, and return the total number of pending items. The test results will be displayed on the test console (or command-line interface if you are using terminal/cmd) and on LambdaTest dashboard.

Execute the Test

Use the below command in your terminal/cmd to execute the Ruby test.

ruby LambdaTest.rb

Configuring Ruby Capabilities for Selenium Automation

As mentioned earlier, you’ll have to configure test script for every language that you’re using to connect with LambdaTest Selenium Automation Grid. In the above Ruby code, the first thing you will notice is the invoking of remote WebDriver instead of the native browser Webdrivers. So, if you want to run this test with Firefox browser on your local computer, then you will have to use Firefox browser driver like this:

  • Local Driver
driver = Selenium::WebDriver.for :firefox

But, with LambdaTest Selenium Grid, the code will be modified to the below command:

  • Remote Web Driver
driver = Selenium::WebDriver.for(:remote,:url => “https://”+lt_user+”:”+lt_appkey+”@hub.lambdatest.com/wd/hub”,  :desired_capabilities => caps)

Browser/OS Test Configuration for Ruby

capabilities = Selenium::WebDriver::Remote::Capabilities.new
capabilities[“build”] = “your build name”
capabilities[“name”] = “your test name”
capabilities[“platform”] = “OS X Yosemite” // Selected Operating System
capabilities[“browserName”] = “Chrome”    // Selected browser name
capabilities[“version”] = “71.0”,        // Selected browser version
capabilities[“resolution”] = “1920x1080”, // Selected screen resolution
capabilities[“selenium_version”] = “3.13.0”, // Selected Selenium version
capabilities[“visual”] = true,
capabilities[“chrome.driver”] = 2.43

The most important capabilities for Ruby are 'browserName,' 'version,' and 'platform.’

Frameworks for Ruby Selenium Automation

To use the Lambdatest Selenium Automation Grid with a Ruby-based framework, there are two testing framework available – Rspec and Test::Unit.

  • RSpec – It is different from other traditional unit testing frameworks like JUnit as it is a behavior-driven development tool. Although it has a rich and powerful domain-specific language, it is very simple and easy to use.
  • Test::Unit – It is a unit testing framework and comes bundled with Ruby. It helps you design, debug, and evaluate your code quickly. The Test::Unit test cases are wrapped with a collection of test methods that allows you to set up and tear down the same test fixture for each test easily.

Both these frameworks have similar capabilities to Ruby.

Conclusion:

Different web applications are developed in different languages, so it becomes challenging to automate your cross browser testing with every programming language. But, selenium provides support across multiple languages that make it easy to perform automation testing. And LambdaTest Selenium Automation Grid makes it even easier for you by providing support for numerous languages and testing frameworks for every language. You can efficiently perform selenium automation with LambdaTest across more than 2000 browsers and operating systems.


⇓ Subscribe Us ⇓


If you are not regular reader of this website then highly recommends you to Sign up for our free email newsletter!! Sign up just providing your email address below:


 

Check email in your inbox for confirmation to get latest updates Software Testing for free.


  Happy Testing!!!
 

1 thought on “How to Perform Selenium Automation Using LambdaTest?”

Leave a Comment

Share This Post