Selenium WebDriver with C# Tutorial for Beginners

Selenium WebDriver with C# Tutorial for Beginners

Selenium is the most popular tool to test websites! Join me and thousands of students to learn Selenium Webdriver!


Selenium is a free automation testing tool for web applications. It is able to work with different browsers like Chrome, Firefox, IE, Opera and simulate human like behavior. Selenium is able to interact with all the different elements in a webpage. It can click on them, input text, extract text and much more. By covering all the different functionalities on your website with Selenium tests, you will be able to quickly catch new and reappearing old bugs. This will save your team time and money.

Specially for you, I have prepared a website where you can play around and practice your skills.

The website has special elements designed specificly for the course and for you to be able to easily work with them and learn.

In this course we will focus on Graphic User Interface and Functionality Testing and we will learn how to work with the various selectors that Selenium offers us to use like:

  • Name selector
  • ID Selector
  • Class Name selector
  • CSS Path selector
  • X Path selector

After that we will learn how to work with some special elements like:

  • Input text boxes
  • Check boxes
  • Radio buttons
  • Drop down menus
  • JavaScript Alert boxes

We will also have a few theory lectures in which I will explain when you should use either of these selectors, how to inspect elements and what is an Automation Testing Framework and why do we need to learn how to create one.


Learn More

C# Basics for Beginners - Learn C# Fundamentals by Coding

C# Intermediate: Classes, Interfaces and OOP

Complete C# Unity Developer 2D: Learn to Code Making Games

Full Stack Developers: Everything You Need to Know

VS Code extensions you may not have heard of before

Java to C# – C# to Java

Java to C# – C# to Java

In this post, we bring you a much needed Rosetta Stone — an explanatory bridge between these two technologies

Originally published by Andy Macdonald at https://medium.com
Java and C# are incredibly similar. Both languages are somewhat derived from C++ and from similar first principles.

Java was developed in 1995 to create a language with a simpler programming model than C++ while still preserving some of the same syntax of the language to facilitate developers transitioning to it.

C# was developed in 2000 by Microsoft as part of its .NET drive in order to develop a language and set of technologies that could address some of the perceived weaknesses of the C++ language. It was also developed with quite heavy “inspiration” from the Java language.

Despite the similarities between the languages and sharing some common ground, transitioning from one technology to the other for a developer well-practised in one technology can be quite tricky.

Innovation happens best when there is collaboration between people of different mindsets — yet users of C# and Java can be somewhat tribalistic.

To that end, I thought it would be useful to put together a sort of guide to help people thinking about or starting to transition between these two technologies. It would also be nice in some way to facilitate a bit more collaboration between these two worlds — hopefully to do my bit to reduce the needless gulf that exists between them.

Some of the similarities right off the bat:

Java is a language that runs in a virtual machine environment (JVM) and runs bytecode that the Java compiler generates.

For C#, the situation is similar. It is a language that runs on the .NET framework and the CLR runtime. It uses a similar intermediary language to Java bytecode called MSIL which gets run via CLR.

Naming and Conventions

Some of the key and most immediately obvious differences in nomenclature, syntax, and conventions are:

  • “Projects” (Java) — “Solutions” (C#)
  • In Java, methods use lowerCamelCase (bar.doAThing()), whilst in C# public methods use PascalCase (bar.DoAThing())
  • In C#, interfaces are always prefixed with an I, as in IUserService<T>, instead of UserService<T>** **in Java
  • In Java, a string is a String** **— in C# a string is a string
  • “POJO” (Java) — “POCO” (C#)
  • Packages (Java) — Namespaces (C#)

Package (Java)

package dev.andymacdonald;

// Code goes here

Namespace (C#)

namespace Dev.AndyMacdonald 
{
  // Code goes here
}

Syntax

**Java has <strong>final</strong> variables — C# has **<strong>readonly</strong>

A key difference here is that Java final variables can be assigned once anywhere in the class, whereas C#’s readonly variables can only be assigned in the constructor.

C# has <strong>out</strong> and <strong>ref</strong> parameters to allow passing arguments by reference — Java doesn’t

It can manipulate objects and variables by reference, but in a method, these arguments are passed by a value. With C#, we can override this behaviour with the out and ref keywords.

Annotations (Java) — attributes (C#)

These are basically equivalent concepts and just differ in actual syntax. Both annotations and attributes can be accessed via each language’s respective Reflection API implementation.

Java annotation:

@PersonallyIdentifiable
private String fullName;

C# attribute:

[PersonallyIdentifiable]
private string fullName;

Getters and setters or Project Lombok (Java) — C# properties

C# really overtakes Java here with its built-in properties* *feature. In the standard JDK, there isn’t an equivalent to this, and instead, in Java, getters and setters must be written for each field requiring an accessor.

These are often just generated by the developer with their IDE as a cheat … still a bit tedious, though.

Java getters and setters:


public class Element 
{
   
  private String symbol;   
  private String name;   
  private int atomicNumber;
  public int getAtomicNumber() 
  {
    return this.atomicNumber;
  }
  public String getSymbol() 
  {
    return this.symbol;
  }
  public String getName() 
  {
    return this.name; 
  }
  public void setAtomicNumber(int atomicNumber) 
  {
    this.atomicNumber = atomicNumber;
  }
  public void setName(String name) 
  {
    this.name = name;
  }
  public void setSymbol(String symbol) 
  {
    this.symbol = symbol;
  }
}

Many Java projects incorporate Project Lombok, which adds getters, setters, equals, and hash code (plus other useful boilerplates) at compile time.

Project Lombok — not part of the standard library:

@Getter @Setter
public class Element 
{
   
  private String symbol;   
  private String name;   
  private int atomicNumber;
}

C# built-in properties feature:

public class Element 
{

  public string Symbol { get; set; }     
  public string Name { get; set; }     
  public int AtomicNumber { get; set; }
}

Loops

Java for each loop:

List<Integer> fibNumbers = Arrays.asList(0, 1, 1, 2, 3, 5, 8, 13);
int count = 0;
for (int element: fibNumbers)
{
    count++;
    System.out.println(String.format("Element #%s: %s", count, element));
}
System.out.println(String.format("Number of elements: %s", count));

C# for each loop:

var fibNumbers = new List<int> { 0, 1, 1, 2, 3, 5, 8, 13 };
int count = 0;
foreach (int element in fibNumbers)
{
    count++;
    Console.WriteLine($"Element #{count}: {element}");
}
Console.WriteLine($"Number of elements: {count}");

Implementing interfaces/inheritance

Inheritance and implementing interfaces isn’t drastically different between the two languages. Java uses the extends or implements keywords; C# uses C++ syntax (derivation declaration) B : A for defining inheritance.

Defining and implementing an interface with methods in Java:

package dev.andymacdonald;


import java.util.ArrayList;
import java.util.List;

interface Fish
{
   void swim();
}

class Salmon implements Fish
{

   public void swim()
   {
      System.out.println("Salmon.Fish");
   }
}

class Cod implements Fish
{
   public void swim()
   {
      System.out.println("Cod.Swim");
   }
}

public class Program
{
   public static void main()
   {
      List<Fish> fishes = new ArrayList<>();
      fishes.add(new Salmon());
      fishes.add(new Cod());

      for (Fish fish : fishes)
      {
         fish.swim();
      }
   }
}

Defining and implementing an interface with methods in C#:

using System;
using System.Collections.Generic;

namespace Dev.AndyMacdonald 
{
    interface Fish
    {
        void Swim();
    }
    class Salmon : Fish
    {
        public void Swim()
        {
            Console.WriteLine("Salmon.Fish");
        }
    }
    class Cod : Fish
    {
        public void Swim()
        {
            Console.WriteLine("Cod.Swim");
        }
    }
    class Program
    {
        static void Main()
        {
            List<Fish> fishes = new List<Fish>();
            fishes.Add(new Salmon());
            fishes.Add(new Cod());
            foreach (Fish fish in fishes)
            {
                fish.Swim();
            }
        }
    }
}

Pointers

Quite simply, Java just doesn’t do pointers, whereas in C# it is possible to do pointer arithmetic and manipulation.

 unsafe {
  int a = 25;
  int * ptr = &a;
  Console.WriteLine($"Value of pointer is {*ptr}");
}

IDE

Visual Studio

C# developers traditionally and typically use the Visual Studio IDE. This is a situation borne out of the origins of .NET being a closed-source technology. Microsoft developed Visual Studio** **to be a one-stop shop for all things .NET.

Java went down a different route, offering much more developer choice in tooling from the outset. That’s why there’s a much greater range of IDEs for Java development (e.g., IntelliJ, Eclipse, NetBeans). Gradually the landscape for .NET developers has shifted, and more IDEs and developer choice has been offered over the years.

IntelliJ (Java) — Rider (C#)

Users of JetBrains IDEs will find the transition from one IDE to another very smooth if they choose to make a switch to the respective JetBrains IDE in the technology they are targeting. Keyboard shortcuts, IDE layout, and even some plugins are equivalent or comparable — virtually the same IDE.

Dependency Management

Maven (Java) — NuGet and dotnet CLI (C#)

Maven is a tool responsible for dependency management and the life cycle of the building of typically Java and JVM applications. That said, it is pretty flexible, has 1000s of plugins, and can be used to build applications of other languages, such as PHP and JavaScript.

The configurable unit of maven is a pom.xml file that every maven project has. For a project’s submodules, it is possible to have a pom file per submodule which inherits from a parent. Maven uses a remote server or repository of some kind to host and retrieve packages.

Maven pom.xml file (Java):

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>dev.andymacdonald</groupId>
    <artifactId>fish-app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

At the simplest level, you can test and build a Maven project with the following command:

mvn clean install

And create a package with this:

mvn clean package

And finally, deploy a package like this:

mvn clean deploy

NuGet fulfills a similar, though not identical role in .NET to Maven. NuGet can use a few different configuration files but commonly uses .csproj*. *As with Maven, NuGet uses a server/repository that can host packages.

NuGet .csproj file:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <AssemblyName>MSBuildSample</AssemblyName>
    <OutputPath>Bin\</OutputPath>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="helloworld.cs" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="MyDependency" version="1.0.0" />
  </ItemGroup>  
  <Target Name="Build">
    <MakeDir Directories="$(OutputPath)" Condition="!Exists('$(OutputPath)')" />
    <Csc Sources="@(Compile)" OutputAssembly="$(OutputPath)$(AssemblyName).exe" />
  </Target>
</Project>

NuGet’s primary role is package management, construction, and deployment. Java developers will notice that it doesn’t really have the same concept of build phases as Maven does. Additionally, .NET developers don’t tend to edit their build files manually as Java developers do with pom.xml files, preferring to manipulate them in their IDE instead.

Packages can be built, packaged, and deployed to NuGet with the following nuget commands:

nuget spec
nuget pack {nuspec file}
nuget push {package file} {apikey} -Source {host url}

If you want to run the tests for your .NET application, you can run the following dotnet CLI command:

dotnet test

The dotnet CLI can also be used as a wrapper around nuget commands.

Application Servers

Apache Tomcat (Java) — IIS (ASP.NET)

Tomcat is an open-source web server and servlet container from the Apache Foundation. Though there are many other application servers used widely in Java, it is a pretty common choice for most enterprise-software companies. It works across pretty much every operating system (e.g., Windows, Unix, Linux, and Mac OS).

.NET projects are typically deployed on IIS, a web server that only runs on Windows. While its portability is limited, it’s a pretty popular choice for Windows developers because of its ease of use and simplicity while still offering some advanced configuration options.

… But Wait!

For .NET Core web applications, you can package them to run as standalone web applications — allowing you to run them like this:

dotnet <app_assembly>.dll

In the same way you can run a Java Spring Boot web*** ***application (which has a self-contained Tomcat server):

java -jar <my-application>.jar

And visit your shiny new web app like this:

http://<serveraddress>:<port>

Libraries and Frameworks

Spring Framework (Java) — ASP.NET (C#)

The Spring Framework is a framework and IoC container for Java. In short, the Spring framework is responsible for instantiating objects (beans) and managing the life cycle of these beans in memory.

Create an ApplicationContext* *(similar to the concept of a Startup in ASP.NET). This example uses Spring Boot:

@SpringBootApplication
public class HumanApplication
{
   public static void main(String[] args) 
   {
      SpringApplication.run(HumanApplication.class, args);
   }
}

Create an interface:

public interface Organ<T>
{  
   void function();
}

Implement the Organ<T> interface:

@Component
public class Heart implements Organ<Heart>
{
    public Heart() {}
    public void function() 
    {
        System.out.println("Buh-dump");
    }
}

Constructor injection of Organ dependencies list into a Human service:

@Service
public class Human 
{
    private static final int MAX_SECONDS_OF_LIFE = 3000;
    private List<Organ> organs;
    public Human(List<Organ> organs) 
    {
        this.organs = organs;
    }
    @PostConstruct
    public void live() 
    {
        for (int i = 0; i < MAX_SECONDS_OF_LIFE; i++) 
        {
            organs.forEach(organ -> organ.function());
        }
    }
}

Run the application …

It’s aliiiiiiive:

Buh-dump
Buh-dump
Buh-dump
Buh-dump
...

Spring also ships with a handy suite of modules and packages.

In the core Spring packages, and in the convention-over-configuration extension to the framework, Spring Boot, useful combinations of existing and bespoke technologies are provided for developers wanting access to common libraries to kickstart a project with all that they may need, rather than having to write or track down these utilities themselves:

  • RestTemplate (spring-web — for constructing REST and HTTP requests)
  • JdbcTemplate (spring-data — for constructing JDBC queries and statements)
  • Spring Security (for creating and managing application security models)
  • ObjectMapper (spring-core — useful utility for mapping POJOs from Jackson)
  • etc.

ASP.NET fulfills a similar role in the world of C#, providing IoC functionality, commonly used technologies, and utilities in a single framework. However, ASP.NET generally only provides IoC functionality for web applications, whereas the Spring Framework provides this for any application type.

In terms of dependency inversion, it is possible to do very similar things in ASP.NET as in Spring.

As before, define the needed interface and concrete implementation:

public interface Organ<T>
{  
   void Function();
}
public class Heart : Organ<Heart>
{
    public Heart() {}
    public void Function() 
    {
        Console.WriteLine("Buh-dump");
    }
}

Invoke functions of injected dependencies:

public class Human
{

   private List<IOrgan> _organs;
 
   public Human(List<IOrgan> organs)
   {
      _organs = organs;
      this.Live();
   }
   public void Live()
   {
      organs.ForEach(organ =>
      {
         organ.Function();
      });
   }
}

Define a Startup and register services:

public class Startup  
{    
  public void ConfigureServices(IServiceCollection services)
  {    
    services.AddTransient<IList<IOrgan>>(p => p.GetServices<IOrgan>().ToList());
  }
}

ASP.NET also fulfills the role of providing many useful libraries and utilities to accelerate development of your project.

Streams (Java) — LINQ (C#)

Both Java and C# have mechanisms to simplify the reduction of data sets — Streams and LINQ.

There are some differences and gaps between the two technologies but if you have familiarity with one, you’ll be able to get up and running fairly quickly with the other.

Java Streams:

List<Student> studentList = Arrays.asList( 
    new Student(1, "John", 18, 1),
    new Student(2, "Steve", 21, 1),
);
List<String> studentNames = studentList.stream()
    .filter(s -> s.getAge() > 18)
    .filter(s -> s.getStandardID() > 0)
    .map(s -> s.getName()).collect(Collectors.toList());
studentNames.forEach(name -> System.out.println(name));

LINQ Query (C#):

IList<Student> studentList = new List<Student>() { 
    new Student() { StudentID = 1, StudentName = "John", Age = 18, StandardID = 1 } ,
    new Student() { StudentID = 2, StudentName = "Steve",  Age = 21, StandardID = 1 }
};
var studentNames = studentList.Where(s => s.Age > 18)
                        .Where(st => st.StandardID > 0)
                        .Select(s => s.StudentName);
foreach(var name in studentNames) {   
    Console.WriteLine(name);
}

Apache Commons (Java) — CommonLibrary.NET (C#)

Apache Commons*** ***provides Java developers with a collection of several independently released, useful components and utilities for the purposes of accelerating development.

If you’re in need of a utility to work with ZIP files or a set of utilities for working with mathematical expressions and formulae, then Apache Commons has you covered.

In a similar way, CommonLibrary.NET covers these bases too — there are some key differences in naming of some components and modules, but for the most part, they are pretty much equivalent in their purpose.

That said, unlike Apache Commons, CommonLibrary.NET is quite old and isn’t very commonly used in projects anymore. If you’re after a continuously updated, curated list of libraries for each respective technology, I highly recommend these two lists:

akullpp/awesome-java

quozd/awesome-dotnet

Testing Libraries

JUnit (Java) — NUnit (C#)

Java’s ever-dependable JUnit library has a direct equivalent in C#.

NUnit has almost equivalent functionality to JUnit and is a popular choice for C# developers.

JUnit:

@Test
public void complexNumberTest()
{
    ComplexNumber result = someCalculation();
    Assert.assertEquals("Real", 5.2, result.getRealPart());
    Assert.assertEquals("Imaginary" 3.9, result.getImaginaryPart());
}

NUnit:

[Test]
public void ComplexNumberTest()
{
    ComplexNumber result = SomeCalculation();
    Assert.Multiple(() =>
    {
        Assert.AreEqual(5.2, result.RealPart, "Real");
        Assert.AreEqual(3.9, result.ImaginaryPart, "Imaginary");
    });
}

(Rumour has it NUnit started life as the JUnit source code modified to run in C#.)

Mockito (Java) — Moq (C#)

As with JUnit and NUnit, comparable functionality exists between Java’s Mockito and C#’s Moq library.

Mockito:

Foo mockFoo = mock(Foo.class);
when(mockFoo.doSomething("ping")).thenReturn(true);

Moq:

var mock = new Mock<IFoo>();
mock.Setup(foo => foo.DoSomething("ping")).Returns(true);

That’s It

Thanks for Reading!

I obviously couldn’t fit every difference, similarity, and detail in this article —* *it’s already far too long.

I hope at least I’ve covered enough ground to make you feel confident to make a switch and see how the other half lives.

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Java Tutorial for Absolute Beginners

100+ Java Interview Questions and Answers In 2019

Python vs Java: Understand Object Oriented Programming

Angular 7 + Spring Boot CRUD Example

Build a Simple CRUD App with Spring Boot and Vue.js

Getting started with Selenium Automation Testing

Getting started with Selenium Automation Testing

Selenium is an open source tool which is used for automating the tests carried out on web browsers (Web applications are tested using any web browser). Take a look at how you can get going with the most popular automation testing platform

Selenium is an open source tool which is used for automating the tests carried out on web browsers (Web applications are tested using any web browser). Take a look at how you can get going with the most popular automation testing platform

Selenium has become very popular among testers because of the various advantages it offers. When we talk about automation testing, the first thing that often comes to our mind is our favorite automation testing tool. Selenium won the hearts of many testers and developers with its simplicity, availability, and ease of use. With its advent in 2004, Selenium made the life of automation testers easier and is now a favorite tool for many automation testers.

What is Selenium?

Selenium was invented with the introduction of a basic tool named as “JavaScriptTestRunner,” by Jason Huggins at ThoughtWorks to test their internal Time and Expenses application. Now it has gained popularity among software testers and developers as an open source portable automation testing framework. It has the capability to automate browsers with specific browser bindings for automating web applications for testing purposes. It is a suite of four tools designed for different purposes. Let’s get to know Selenium in detail and the different tools that it offers.

Selenium Suite of Tools

Selenium has four major components with a different approach for automation testing which is popular as the Selenium suite of tools. Every software tester or developer choose tools out of it depending upon the testing requirement for the organization.

Selenium RC (Remote Control)

Selenium Core was the first tool in the suite of tools. However, it was deprecated as it had some issues related to cross-domain testing because of same origin policy. So, to overcome that, Selenium Remote Control (Selenium RC) was introduced after Selenium Core. RC turned out to be a solution to the cross-domain issue. RC has an HTTP proxy server which helps in tricking the browser into believing that both the Selenium Wore and web app which is being tested are from the same domain, removing the cross-domain issue.

Selenium RC is divided into two parts which help in overcoming the cross-domain issue:

  1. Selenium Remote Server
  2. Selenium Remote Client

But the major issue with RC was the time taken to execute a test. As the Selenium server communicates using HTTP requests, it was more time-consuming. Because of this limitation, RC also is now largely obsolete.

Selenium IDE

Selenium IDE, earlier known as Selenium recorder, is a tool used to record, edit, debug, and replay functional tests. Selenium IDE is implemented as an extension to the Chrome browser and an add-on in Firefox browser. With the Selenium IDE plugin, you can record and export tests in any of the supported programming languages like Ruby, Java, PHP, Javascript, and more.

Selenium Grid

Selenium Grid is based on a hub-node architecture. With Selenium Grid, you can run parallel test sessions across different browsers. The hub controls Selenium scripts running on different nodes (specific browsers inside an OS) and test scripts running on different nodes can be written in any programming language.

Selenium Grid was used with RC to test multiple tests on remote machines. Now, as people find **WebDriver **works better than RC, Grid works with both WebDriver and RC.

Selenium WebDriver

Selenium WebDriver is an enhanced version of Selenium RC and the most used tool. It accepts commands via the client API and sends them to browsers. Simply put, Selenium WebDriver is a browser-specific driver which helps in accessing and launching the different browsers. It provides an interface to write and run automation scripts. Every browser has different drivers to run tests.

  • Mozilla Firefox uses Firefox Driver (Gecko Driver)
  • Google Chrome uses Chrome Driver
  • Internet Explorer uses Internet Explorer Driver
  • Opera uses Opera Driver
  • Safari uses Safari Driver and
  • HTM Unit Driver used to simulate browsers using headless browser HtmlUnit

Selenium Client API

The Client API is the latest tool in the Suite of tools. With Selenium Client API, you can write test scripts in various programming languages instead of writing test scripts in Selenese. The Selenium Client API is available for Java, JavaScript, C#, Ruby, and Python. These scripts can communicate with Selenium with predefined commands and functions of Client API.

Why Use Selenium for Automation Testing?

Since we are now familiar with Selenium and its suite of tools, let’s find out the various benefits of Selenium which make it stand from the crowd as a tool for automation testing:

  1. Open-Source: Since it is an open source tool, it doesn’t require any licensing costs, which give it an upper hand over other automation testing tools.
  2. Tool for Every Need: As mentioned earlier, Selenium has a suite of tools, so it suits every need of the users. You can use various tools like WebDriver, Grid, and IDE for fulfilling your different needs.
  3. Supports All Major Languages: The major challenge that a tester or developer faces with an automation testing tool is the support for languages. Since Selenium supports all major languages like Java, JavaScript, Python, Ruby, C#, Perl, .Net and PHP, it is easier for testers to use.
  4. Browser and Operating System Support: Selenium supports different browsers like Chrome, Firefox, Opera, Internet Explorer, Edge, and Safari and different operating systems like Windows, Linux, and Mac. This makes it flexible to use.
  5. Community Support: Selenium has an active open community which helps you solve your issues and queries related to it. This makes it the best choice as your automation testing tool.

Here’s a quick comparison table of Selenium with other available tools:

Since **Selenium WebDriver **is the most used tool, we’ll be using it to execute some test cases. To understand the complete process on a very simple level, Selenium **WebDriver Architecture **consists of:

Basically, Selenium WebDriver works in three layers: Browser Driver, Remote Driver, and Language Bindings.

Core Components of WebDriver Architecture

Selenium Client Library/Language Bindings

Selenium bindings/client libraries are created by developers to support multiple programming languages. For instance, if you want to use the browser driver in Python, use the Python bindings. You can download all the bindings on the official website.

JSON Protocol Over HTTP

JavaScript Object Notation is used as a data transfer protocol to send data from a server to a client on the web. With JSON, it is very easy to write and read data with data structures like Array and Object support. This wire protocol provides a transport mechanism and defines a RESTful web service using JSON over HTTP.

Browser-Specific Driver

Each web browser has a specific browser driver for Selenium bindings. The browser driver accepts commands from the server and sends it to the browser without loss of any internal logic of browser functionalities. Browser drivers are also specific to programming languages like Ruby, C#, Java, and more for web automation.

Here are the steps when we run any test script using WebDriver:

  1. An HTTP request gets generated for every Selenium command and gets sent to browser driver.
  2. The specific browser driver receives the HTTP request through the HTTP server.
  3. HTTP Server sends all the steps to perform a function, which are executed on the browser.
  4. The test execution report is sent back to server and HTTP server sends it to the Automation script.

Browsers

**Selenium WebDriver **supports all the major browser like Google Chrome, Mozilla Firefox, Internet Explorer, and Safari browsers.

Setting Up Selenium on Your Local Machine

Let’s understand the steps of how we can configure Selenium in your local machine and running a test in your local browser.

  1. Install Code editor or IDE (like Eclipse or IntelliJ)

Note: We’ll be using IntelliJ code editor for writing Automation script.

  1. Download and install Java Runtime environment in your local system.
  2. Download Java Development Kit
  3. Download and install all Java Selenium Files (Selenium Server Standalone)
  4. Install Browser Specific Drivers ( In this blog, we’ll perform Automation on Chrome, so Chrome Driver for this case)
Sample Selenium Script for Web Automation

Here is the sample automation script which can be run to automate the testing process on the local chrome browser. Since we are using IntelliJ as our code editor, so we’ll write the same in IntelliJ.

Sample Script

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestSelenium {
public static void main(String[] args){
System.setProperty("webdriver.chrome.driver","C:\\Users\\Admin\\Desktop\\LT Automation\\chromedriver_win32\\chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("https://hackr.io/");
try {
WebElement signup = driver.findElement(By.xpath("//*[@id="navbarCollapse"]/ul/li[2]/a"));
signup.click();
WebElement login= driver.findElement(By.xpath("//*[@id="modalSignUp"]/div/div/div/div/div[4]/p/a"));
login.click();
String windowHandle = driver.getWindowHandle();
WebElement TextBox = driver.findElement(By.xpath("//*[@id="login-modal-form"]/div[1]/div/input"));
TextBox.sendKeys("[email protected]");
WebElement Password = driver.findElement(By.xpath("//*[@id="login-modal-form"]/div[2]/div/input"));
Password.sendKeys("sample-password");
WebElement proceed = driver.findElement(By.xpath("//*[@id="login-modal-form"]/div[4]/button"));
proceed.click();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

This code will launch a website (here, https://hackr.io/), find “Signup/Login” element, click on the Signup/login button, then go to the login page by finding “Login.” After that, enter the credentials to the login page and click the login button to be redirected to Hackr.io homepage.

Online Selenium Grid

The major challenge in running Selenium on a local machine is the limited number of browsers in the local machine. Since you can have only one version of a particular browser installed in your local machine, if the need comes to test on some downgraded or upgraded version of that browser, you’ll need to upgrade or downgrade the already installed browser in your local machine. Also, you can install only a specific number of browsers in the system. So, if the need comes it becomes almost impossible to test across all browsers and operating systems. That's where an online Selenium Grid can help.

With the help of an online Selenium Grid on the cloud, you can test across all the browsers, browser versions, operating systems, resolutions for cross-browser compatibility. Online platforms which provide Selenium Grids, like LambdaTest, SauceLabs, and BrowserStack, can help you perform cross-browser tests on cloud grid of various browsers-OS combinations.

Common Selenium Command and Operations

While writing an automation script, you will be using many repeated commands and doing various operations. Let’s have a quick look at the most common and used commands in Selenium automation testing.

**Page Visit: **The first thing to do visit a webpage to start automation testing.

driver.get("https://hackr.io/");

**Find an Element: **Find elements to automate them.

// find just one, the first one Selenium finds
WebElement element = driver.findElement(locator);
// find all instances of the element on the page
List<WebElement> elements = driver.findElements(locator);

**Actions on Elements: **Work on found elements.

// chain actions together
driver.findElement(locator).click();
// store the element and then click it

WebElement element = driver.findElement(locator);
element.click();

**Multiple Element Commands: **Common commands to click, submit, clear, input, etc.

element.click(); // clicks an element
element.submit(); // submits a form
element.clear(); // clears an input field of its text
element.sendKeys("input text"); // types text into an input field

**Question Commands: **Check conditions for elements.

element.isDisplayed(); // is it visible to the human eye?
element.isEnabled(); // can it be selected?
element.isSelected(); // is it selected?

**Get your Info: **Commands for retrieving information for an element.

// directly from an element
element.getText();
// by attribute name
element.getAttribute("href");

To Sum Up

Selenium is one of the best automation testing tools to automate web browser interactions. You can perform automation testing by writing code in any of your preferred language supported by Selenium and can easily run your automation script to automate testing of an application or a process. Its ease of use makes it different from other tools and with the help of an online grid you can even run your tests in parallel across more than one browser. So, what are you waiting for? Write a beautiful automation Script and test your website! If you have any questions, let us know in the comments section below.

Happy Testing!