TestCafe vs Selenium : Which is better?

In the realm of web testing frameworks, TestCafe and Selenium stand out for their unique approaches to automation testing. TestCafe, a Node.js tool, offers a straightforward setup and testing process without requiring WebDriver.

Its appeal lies in its ability to run tests on any browser that supports HTML5, including headless browsers, directly without plugins or additional tools.

On the other hand, Selenium, a veteran in the field, is renowned for its extensive browser support and compatibility with multiple programming languages, making it a staple in diverse testing scenarios.

This comparison delves into their technical nuances, assessing their capabilities, ease of use, and flexibility to determine which framework better suits specific testing needs.

Firstly, we’ll understand the role of both automation tools and later see a quick comparison between them.

All About TestCafe

Developed by DevExpress, TestCafe offers a robust and comprehensive solution for automating web testing without relying on WebDriver or any other external plugins.

It provides a user-friendly and flexible API that simplifies the process of writing and maintaining test scripts. Some of its key features include:

  1. Cross-browser Testing: TestCafe allows you to test web applications across multiple browsers simultaneously, including Chrome, Firefox, Safari, and Edge, without any browser plugins.
  2. Easy Setup: With TestCafe, there’s no need for WebDriver setup or additional browser drivers. You can get started with testing right away by simply installing TestCafe via npm.
  3. Automatic Waiting: TestCafe automatically waits for page elements to appear, eliminating the need for explicit waits or sleep statements in your test scripts. This makes tests more robust and reliable.
  4. Built-in Test Runner: TestCafe comes with a built-in test runner that provides real-time feedback during test execution, including detailed logs and screenshots for failed tests.
  5. Support for Modern Web Technologies: TestCafe supports the testing of web applications built with modern technologies such as React, Angular, Vue.js, and more, out of the box.

 

Read About:Learn How to Use Testcafe For Creating Testcases Just Like That

Installation of TestCafe

Installing TestCafe is straightforward, thanks to its Node.js foundation. Before you begin, ensure you have Node.js (including npm) installed on your system.

If you haven’t installed Node.js yet, download and install it from the official Node.js website.

Here are the steps to install TestCafe:

Step 1: Open a Terminal or Command Prompt

Open your terminal (on macOS or Linux) or command prompt/powershell (on Windows).

Step 2: Install TestCafe Using npm

Run the following command to install TestCafe globally on your machine. Installing it globally allows you to run TestCafe from any directory in your terminal or command prompt.

npm install -g testcafe

Step 3: Verify Installation

To verify that TestCafe has been installed correctly, you can run the following command to check its version:

testcafe -v

If the installation was successful, you will see the version number of TestCafe output to your terminal or command prompt.

Step 4: Run Your First Test

With TestCafe installed, you can now run tests. Here’s a quick command to run an example test on Google Chrome. This command tells TestCafe to use Google Chrome to open a website and check if the title contains a specific text.

testcafe chrome test_file.js

Replace test_file.js with the path to your test file.

Note:

  • If you encounter any permissions issues during installation, you might need to prepend sudo to the install command (for macOS/Linux) or run your command prompt or PowerShell as an administrator (for Windows).
  • TestCafe allows you to run tests in most modern browsers installed on your local machine or on remote devices without requiring WebDriver or any other testing software.

That’s it! You’ve successfully installed TestCafe and are ready to start automating your web testing.

How To Run Tests In TestCafe

Running tests with TestCafe is straightforward and does not require WebDriver or any other testing software. Here’s how you can run tests in TestCafe:

1. Write Your Test

Before running tests, you need to have a test file. TestCafe tests are written in JavaScript or TypeScript. Here’s a simple example of a TestCafe test script (test1.js) that navigates to Google and checks the title:

import { Selector } from 'testcafe';

fixture `Getting Started`
.page `https://www.google.com`;

test(‘My first test’, async t => {
await t
.expect(Selector(‘title’).innerText).eql(‘Google’);
});

2. Run the Test

Open your terminal (or Command Prompt/PowerShell on Windows) and navigate to the directory containing your test file.

To run the test in a specific browser, use the following command:

testcafe chrome test1.js

Replace chrome with the name of any browser you have installed (e.g., firefox, safari, edge). You can also run tests in multiple browsers by separating the browser names with commas:

testcafe chrome,firefox test1.js

3. Running Tests on Remote Devices

TestCafe allows you to run tests on remote devices. To do this, use the remote keyword:

testcafe remote test1.js

TestCafe will provide a URL that you need to open in the browser on your remote device. The test will start running as soon as you open the link.

4. Running Tests in Headless Mode

For browsers that support headless mode (like Chrome and Firefox), you can run tests without the UI:

testcafe chrome:headless test1.js

5. Additional Options

TestCafe provides various command-line options to customize test runs, such as specifying a file or directory, running tests in parallel, or specifying a custom reporter. Use the --help option to see all available commands:

testcafe --help

Example: Running Tests in Parallel

To run tests in parallel in three instances of Chrome, use:

testcafe -c 3 chrome test1.js

All About Selenium

Selenium provides a suite of tools and libraries for automating web browsers across various platforms. Selenium WebDriver, the core component of Selenium, allows testers to write scripts in multiple programming languages such as Java, Python, C#, and JavaScript. I

ts key features include:

  1. Cross-browser and Cross-platform Testing: Like TestCafe, Selenium supports cross-browser testing across different web browsers such as Chrome, Firefox, Safari, and Internet Explorer.
  2. Large Community Support: Selenium has a large and active community of developers and testers who contribute to its development, provide support, and share best practices.
  3. Flexibility: Selenium offers flexibility in terms of programming language and framework choice. You can write test scripts using your preferred programming language and integrate Selenium with popular testing frameworks such as JUnit, TestNG, and NUnit.
  4. Integration with Third-party Tools: Selenium can be easily integrated with various third-party tools and services such as Sauce Labs, BrowserStack, and Docker for cloud-based testing, parallel testing, and containerized testing.
  5. Support for Mobile Testing: Selenium Grid allows you to perform automated testing of web applications on mobile devices and emulators, making it suitable for mobile testing as well.

How To Install Selenium

Installing Selenium involves setting up the Selenium WebDriver, which allows you to automate browser actions for testing purposes.

The setup process varies depending on the programming language you’re using (e.g., Java, Python, C#, etc.) and the browsers you intend to automate. Below is a general guide to get you started with Selenium in Java and Python, two of the most common languages used with Selenium.

For Java

Install Java Development Kit (JDK):

  • Ensure you have the JDK installed on your system. If not, download and install it from the official Oracle website or use OpenJDK.
  • Set up the JAVA_HOME environment variable to point to your JDK installation.

Install an IDE (Optional):

  • While not required, an Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse can make coding and managing your project easier.

Download Selenium WebDriver:

Add Selenium WebDriver to Your Project:

  • If using an IDE, create a new project and add the Selenium JAR files to your project’s build path.
  • For Maven projects, add the Selenium dependency to your pom.xml file:
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>LATEST_VERSION</version>
</dependency>
</dependencies>

For Python

Install Python:

  • Ensure Python is installed on your system. If not, download and install it from the official Python website.
  • Make sure to add Python to your system’s PATH during installation.

Install Selenium WebDriver:

  • Open your terminal (Command Prompt or PowerShell on Windows, Terminal on macOS and Linux).
  • Run the following command to install Selenium using pip, Python’s package installer:
pip install selenium

Browser Drivers

Regardless of the language, you will need to download browser-specific drivers to communicate with your chosen browser (e.g., ChromeDriver for Google Chrome, geckodriver for Firefox). Here’s how to set them up:

Download Browser Drivers:

Set Up the Driver:

  • Extract the downloaded driver to a known location on your system.
  • Add the driver’s location to your system’s PATH environment variable.

Verify Installation

To verify that Selenium is installed correctly, you can write a simple script that opens a web browser:

For Java

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumTest {
public static void main(String[] args) {
System.setProperty(“webdriver.chrome.driver”, “PATH_TO_CHROMEDRIVER”);
WebDriver driver = new ChromeDriver();
driver.get(“https://www.google.com”);
}
}

For Python

from selenium import webdriver

driver = webdriver.Chrome(executable_path=‘PATH_TO_CHROMEDRIVER’)
driver.get(“https://www.google.com”)

Replace PATH_TO_CHROMEDRIVER with the actual path to your ChromeDriver.

This guide should help you get started with Selenium. Remember, the exact steps may vary based on your development environment and the browsers you want to automate.

Also Read : Why is TestNG Awesome? Advantages of Integrating it with Selenium

Comparison Between TestCafe And Selenium

Feature TestCafe Selenium
Language Support JavaScript, TypeScript Java, C#, Python, Ruby, JavaScript, Kotlin, PHP
Browser Support Runs on any browser that supports HTML5. Includes support for headless browsers and mobile browsers via device emulators. Wide range of browsers including Chrome, Firefox, Internet Explorer, Safari, Opera, and Edge. Requires additional drivers for each browser.
WebDriver Requirement Does not require WebDriver or any external dependencies. Requires WebDriver to interact with web browsers.
Installation and Setup Simple setup with no dependencies other than Node.js. Easily installed via npm. More complex setup due to the need for installing WebDriver for each browser.
Test Execution Executes tests directly in the browser using a server. Can run tests on remote devices. Communicates with browsers through the WebDriver protocol.
Parallel Test Execution Built-in support for running tests concurrently across multiple browsers or devices. Supports parallel test execution with additional tools like Selenium Grid or third-party frameworks.
Cross-Browser Testing Simplified cross-browser testing without additional configurations. Requires configuration and setup for each WebDriver to enable cross-browser testing.
Integration with CI/CD Easy integration with popular CI/CD tools like Jenkins, TeamCity, Travis CI, and GitLab CI. Broad support for integration with various CI/CD systems.
Mobile Testing Supports mobile testing through device emulation in browsers. Supports real mobile devices and emulators through Appium integration.
Record and Replay Provides a feature to record actions in the browser and generate test code (with TestCafe Studio). Third-party tools and plugins are required for record and replay capabilities.
Community and Support Active community with support available through forums and chat. Commercial support is available through DevExpress for TestCafe Studio. Very large and active community with extensive resources, forums, and documentation.
Use Case Ideal for teams looking for a quick setup and easy JavaScript/TypeScript integration. Best suited for projects that require extensive language support and integration with various browser drivers and mobile testing through Appium.

Conclusion: Which one is Better? Based On Our Experience.

Both TestCafe and Selenium offer powerful capabilities for web testing, but the choice between them depends on specific project requirements, such as the preferred programming language, ease of setup, browser support, and testing environment complexity.

TestCafe might be more appealing for projects that prioritize ease of use and quick setup, while Selenium provides greater flexibility and language support, making it suitable for more complex automation tasks that may involve a wider range of browsers and integration with mobile testing frameworks like Appium.

11 Tips and Tricks For Appium and Selenium

Selenium and Appium are two well-known automation testing tools. Selenium is largely leveraged for testing web applications whereas Appium is widely used for testing mobile applications. Bundled with many features, both these tools are highly recommended for software testing.
But you need to have a proper understanding of these appium and selenium tools to get best out of them.  There are few tips and tricks that can help you get best out these tools and leverage them to their best abilities.
Let’s make our job easier with these veteran Tips and Tricks about Appium and Selenium.

The Use of Waits: 

Using Thread.Sleep() is a common method of “waiting” while any processing is going on. But it possesses a few drawbacks. Here is how we can overcome it.
a)    WebDriverWait.  It census your query every 500ms, and return when the wait condition is fulfilled. WebDriverWait can explicitly put a maximum threshold to elude locks and infinite waiting.
b)    FindElementBy / FindElement(..): Second method is by invoking FindElementBy or just FindElement(..). FindElementBy waits until the element is found and returns null if maximum wait time passes. But be sure you have to explicitly configure the implicitly waits.
1. Locating Elements
Locating element is not a tough job in selenium and there are many ways to do it. But the haunting part is getting StaleElementReferenceException.
It happens when you assign IWebElement reference but it already has some other location in the DOM. The solution to StaleElementReferenceException is to re-query and reassign the element reference.
2. Sending Keyboard input
Selenium allows sending inputs in two ways. First is by setting “value” property of editable elements by using ExecuteScript() / ExecuteAsyncScript(). Second is to use SendKeys() API.
I would suggest you use ExecuteScript() / ExecuteAsyncScript() method when you are more concerned about filling in a few fields and when you are not concerned about DOM events being fired and concurrent character-by-character verification.
But if you want to focus on real-time validation, the second method i.e. using SendKeys() API will be more apt for you.
3. Executing JavaScript code
You can execute JavaScript in either of the below-given ways depending upon your requirements.
i)    ExecuteScript().ExecuteScript() does not execute the next line of         test code till script execution is returned.
ii)    ExecuteAsyncScript() does not block your test code.
4. Drag & Drop Interfaces
Action Builder API, and the “DragAndDrop” and “DragAndDropToOffset” methods support easy drag and drop interface in Selenium.
5. Switching between windows and iframes
You can easily switch between windows and frames in Selenium.

  1. For iFrames

driver.SwitchTo().Frame(frameElement); //IWebElement

  1. For Windows

driver.SwitchTo().Window(handle);// driver window handle
and then can switch back to the original window by using
driver.SwitchTo().DefaultContent();

  1. Using drivers for multiple browsers

When using the driver API, always refer it by using RemoteWebDriver class for all the browsers used for running tests.
It is good to label your environment in a text/XML file and then deconstruct this and return the correct driver instance.
6. Cleaning UP
When you are done with your testing, you need to free all the resources and close the browser.
For this you can use Close(), Quit(), and Dispose().  Quit() closes all browsers, close() closes the existing browser  while Dispose() calls the quit() and closes all browsers.
Now when we are done with a few tips and tricks of working with selenium, let us now get better in our Apium skills.
Appium is one of the widely used mobile app testing tools. Though its users encounter some common problems while using it…
Here are some tips and tricks that can help you handle some common problems faced in using it and making it’s working more efficient and effective.
So, here we go…
7. Writing cross-platform tests 
One of the major issue in testing mobile apps is we have to write different test scenario for Android and iOS. Having common tests can be a big benefit in terms of saving time and efforts.
Though it gets much easier having the same set of test cases for both if your application is the same from a UI point-of-view.

Read also :  Testcafe Vs Selenium. Which is Better?

Just make sure that the accessibility IDs on corresponding UI elements in each version of the app matches with each other. If it stands true, you can run the same test on both applications. Also, be sure your test sets up the appropriate capabilities for each platform.
Based on different platforms, here are some more and little-known tips and tricks about Appium that can make your testing easier.
8. For All Platforms

  • AutoWebView – it is very useful for Cordova apps and helps to start in the webview context.

9. For Android

  • ignoreUnimportantViews – It is a very useful method to quicken your Android tests.
  • nativeWebScreenshot – Helps you to take a screenshot from UIAutomator. It is very useful if your screenshots from chromedriver are not as expected.

10. For IoS

  • locationServicesAuthorized – It helps you to prevent showing an alert when you are trying to use the user’s location by pre-authorizing location services.
  • Auto[Accept|Dismiss]Alerts – It helps you avoid alerts from disrupting your tests.
  • nativeWebTap – Permits users to use non-javascript taps.
  • safariIgnoreFraudWarning – It is beneficial in cases where your test environment doesn’t have 100% perfect SSL setup.
  • interKeyDelay – Sometimes Appium’s typing speed can cause a problem with your application, in such cases, interKeyDelay can evade the problem.
  • sendKeyStrategy – Helps in avoiding the keyboard altogether.

11. Networking Conditioning
You can use driver.setNetworkConnection(value) to stimulate various states of connectivity when you run your tests.
Hope these tips will prove helpful to you, will be back soon with some more useful testing tips and tricks. So stay tuned!

Selenium Tutorial For Beginners [Step by Step]

Everybody knows about the impeccable selenium! The ultimate tool for testing web applications! for you to learn in detail about how to carry out automation testing, we have written an extensive Selenium tutorial just for you!
This blog comprises of three part,
1. Selenium Tutorial For Beginners
2. Selenium Intermediate Level Tutorial
3. Selenium Advanced level Tutorial

Selenium Tutorial For Beginners

What makes Selenium better?

You don’t need to code anything in Selenium and with this; any beginner will be able to record and play the simplest web application scripts.
Usually, Selenium RC needs a server to be up and running for sending commands to the browser. It is used for cross-browser testing and you can write the code in any language.
Selenium Web Driver is a better version of IDE and RC. It directly sends commands to the browser without the need of a server to be up and running.

Different languages can be used for coding the scripts like Java, C#, PHP, Python, Perl, and Ruby. Selenium Grid is used for parallel testing in multiple browsers and environments. It used the hub and node concept where hub acts as a source of Selenium commands and each node is connected to it.
Now, here we will discuss Selenium WebDriver. How a beginner can start learning Selenium WebDriver and how he can excel in it.
Now, first, we will look at the steps we need to follow to download Selenium Web Driver in your machine.

Ways to download and install Selenium WebDriver

  • You should have Java installed in your machine. This is the pre-requisite for Selenium Web Driver to work.
  • You can visit the page: http://seleniumhq.org/download/ and download the client drivers and language bindings. You have the select binding for Java.
  • This download will be named – selenium-2.25.0.zip.
  • Now, you can import all the Jars in Eclipse. You have to right click on the project and import jar files by selecting all the downloaded jar files. For this, you can click on the Libraries tab and then click on “Add External JARs”.

Now Let’s look the First Selenium WebDriver Script

Let’s take an example of the first Selenium Script which we would create using Selenium basic methods.
Let’s first look at the script in detail. In this script, we will do the following test steps.

  • Go to the home page of the test application
  • Verify the title of the page
  • Do a comparison of the result.
  • Close the browser after the script is done.

package projectSelenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class seleniumTest {
public static void main(String[] args) {
System.setProperty(“webdriver.chrome.driver”,”C:\\chromeDriver.exe”);
WebDriver driver = new ChromeDriver();
String baseUrl = “https://google.com”;
String expectedTitle = “Google”;
String actualTitle = “”;
        // launch Fire fox and direct it to the Base URL
driver.get(baseUrl);
        // get the actual value of the title
actualTitle = driver.getTitle();
/*
* compare the actual title of the page with the expected one and print
* the result as “Passed” or “Failed”
*/
if (actualTitle.contentEquals(expectedTitle)){
System.out.println(“Test Passed!”);
} else {
System.out.println(“Test Failed”);
}
driver.close();
}
}

Things to look at the above code:

  • In the first two lines, we have imported two packages. You have to import – org.openqa.selenium and org.openqa.selenium.firefox.FirefoxDriver.
  • The most important step is to instantiate the browser. This is done by line

WebDriver driver = new ChromeDriver();
//This is done to invoke a chrome browser.
You can invoke a FireFox browser by following line of code
WebDriver driver = new FirefoxDriver();
You can invoke an IE browser by following line of code:
WebDriver driver = new InternetExplorerDriver ();
Also, while invoking a browser you have to pass the path of the executable file. You can do it by following line of code:
System.setProperty(“webdriver.chrome.driver”,”Path of chrome driver”);
System.setproperty(“webdriver.ie.driver”,”Path of ie driver”);

  • Get() method is used to enter a url in a browser.
  • getTitle() method of selenium webdriver is used to fetch the title of a web page.
  • Now, we have to compare the expected title with the actual title.

If(expectedTitle.equals(actualTitle))
{
System.out.println(“TEST PASSED”):
}

  • For terminating the browser, close() method is used. Driver.close() closes the active browser window. If you want to close all the opened browser windows by selenium web driver then you can use driver.quit().
  • You can run this test by right clicking on the program and then select as “Run As” as “Java Application”.
  • Next thing which is of utmost important while writing a test script is to identify web Elements which will be explained in detail in the below section.

Locating Web Elements

Locating web elements is very easy. Various selectors are available for that process. find Elements is one such 2 in which selenium webdriver is used for locating a web element and then, you can perform an action on that.

Know More: Selenium Automation Testing With Cucumber Integration

Let’s see some of the methods by which you can identify web element on a web page.

  • className – It will locate web element based on the class attribute. Eg: By.className(“abc”);
  • cssSelector – used to locate web element based on css selector engine. Eg:- By.cssSelector(“#abc”);
  • id – If some web element has id attribute, then you can directly identify the web element using id tag. Eg:- By.id(“abc”);
  • linkText – It will find a link element by text mentioned by you in the test script. By.linkText(“Login”);
  • name – If any web element has name attached to it then you can identify it using name attribute. Eg: By.name(“name”);
  • partialText – It will find a link element by text containing the text mentioned by you in the test script. By.partialText(“abc”);
  • tagName – It will locate all elements which will have this tag.
  • xpath – It is the most used locator in a selenium test script. It will identify the element using html path. It can be relative or absolute. Absolute xpath traverses the path of the web element by root and relative takes the reference of any web element and then traverse to that specified web element. It is better to refer an element by relative xpath rather than absolute xpath.

Basic Actions on a web element

You can click on a web element by using click() method of selenium web driver. You can locate a web element and then perform an action on it.
Eg: driver.findElement(By.xpath(“”)).click();
Also, you can send keys to a particular web element by using send Keys() method of selenium web driver. You can locate a web element and then you can enter some text in it using sendKeys() method.
Eg: driver.findElement(By.xpath(“”)).sendKeys(“name”);
Also, there are other actions which you can perform on a web element by using action class.
WebElement wb = driver.findElement(By.xpath(“”));
Actions actions = new Actions(Driver);
Actions.moveToElement(wb).build(). Perform ();
You can even switch to alert boxes which come when you click on some webelement. You can do it by switchTo().alert() method.
Eg code:
WebElement wb = driver.findElement(By.xpath(“”));
Wb.click();
Driver.switchTo().alert();
Now, you will be able to access the alert box. You can retrieve the message displayed in the text box by getting the text from it.
String alertMessage = driver.switchTo().alert().getText();
Also, you can accept the alert box by function accept(). You can see the sample code as below:
Driver.switchTo().alert().accept();
You can even check conditional operations on a web element.
Also, check whether a web element is enabled or not. If it will be enabled then you can do some operation on it.
Apart from all these, you can check if some web element is displayed or not. In the case of radio buttons, you can check if the radio button is selected or not. You can do these checks by – isEnabled(), isSelected() and isDisplayed() option.

Waits in Selenium Web Driver

Selenium Web Driver
If you want some step to get completed before any other step then you have to wait for the prior step to get completed. In manual testing, it is very easy to achieve but in automation testing, it is bit tedious and you have to wait for the previous step to get completed or a condition to be fulfilled before moving on wards to the next step.
This can be achieved by adding waits in between. There are two types of wait- explicit and implicit wait. If you are expecting a particular condition to be fulfilled before moving to the next step,
Another feature is that you can use explicit wait while if you just want a universal wait, then you can go ahead to use implicit wait. The implicit wait is used to set the default time out for the whole script.
A perfect automation script is made by adding both type of waits – Explicit and Implicit. You have to judiciously use both types of waits to make an efficient test case.

Know More : Top 50 Selenium Interview Questions and Answers

Explicit Wait

Syntax of Explicit Wait:
WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(“”));
Expected Condition can be used with so many conditions. Some conditions which can be used with it are:

  • alertIsPresent()
  • elementSelectionStateToBe()
  • elementToBeClickable()
  • elementToBeSelected()
  • frameToBeAvaliableAndSwitchToIt()
  • invisibilityOfTheElementLocated()
  • invisibilityOfElementWithText()
  • presenceOfAllElementsLocatedBy()
  • presenceOfElementLocated()
  • textToBePresentInElement()
  • textToBePresentInElementLocated()
  • textToBePresentInElementValue()
  • titleIs()
  • titleContains()
  • visibilityOf()
  • visibilityOfAllElements()
  • visibilityOfAllElementsLocatedBy()
  • visibilityOfElementLocated()

Implicit Wait

Syntax of Implicit Wait:
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
For this, you have to import a package into your code. The package name is java.util.concurrent.TimeUnit;

Selenium Intermediate Level Tutorial

Through the section Selenium Tutorial for Beginners, We gave you the basic info that you need to know about the tool. Now let’s go further and learn much more about this impeccable web app testing tool.
How to upload a file in Selenium test cases?
To upload a file, first, you have to identify the element on which you have to upload your file. There you can directly use sendKeys() function of selenium web driver. You can pass the path of the location in sendKeys. In this way, you will be able to upload a file using selenium web driver.

public static void main(String[] args) {
System.setProperty(“webdriver.gecko.driver”,”path of gecko driver”);
String baseUrl = “http://www.google.com /upload/”;
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
WebElement element = driver.findElement(By.id(“id of element”));
uploadElement.sendKeys(“C:\\newhtml.html”);
//Here,  above you have to pass the path of the file where your file is located.
// Then you can click the upload file link
driver.findElement(By.xpath(“”)).click();
}
How to use a web table in selenium script
You have to access a web table and the elements present in the table. You can get it by making an xpath. Suppose you have had1 0a table with four blocks.
selenium intermediate tutorial
The first thing which you have to do is to find the XPath of the web element in this web table. Let’s say you want to get to the third element in the above web element.
The coding of the above web table is as below:

Selenium Intermediate Level TutorialSelenium Intermediate Level Tutorial
Now, you can analyze that first there is a table and then there is a tbody. In that tbody there are two rows. One row is having two tables. The first row is having two cells – First and Second. The second row is having two cells – Third and Fourth.
Our goal is to reach to the third cell. Let’s try to make the XPath of it.
The XPath of it will be //table/tbody/tr[2]/td[1]
So, the table is the parent node from which we will iterate to go the third element. From there, we will go to the tbody section and then the second row. From there we will get the first column.
Let’s write a script to get the text out of it.
public static void main(String[] args) {
String url = “http://testsite.com/test/write-xpath-table.html”;
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
String txtWebelement = driver.findElement( By.xpath(“//table/tbody/tr[2]/td[1]”).getText();
System.out.println(txtWebelement);
driver.close();
}
}
Let’s take an example of a nested web table. You have to then analyze it carefully and get the XPath of it. Let’s look at the example below to get more information on it.
Selenium Intermediate Level Tutorial:
So, if you want to access the web element which is having text 10-11-12 then you can do it by traversing from the table and then iterating through the rows and columns to reach there.
Xpath would be: //table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]
public static void main(String[] args) {
String url = “http://testsite.com/test/write-xpath-table.html”;
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
String txtWebelement = driver.findElement( By.xpath(“//table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]
”)getText();
System.out.println(txtWebelement);
driver.close();
}
}
This way, you can iterate through the rows and columns to reach to a specific cell from a web table.
Now, one of the most important concepts in selenium which will help you in many cases when you won’t be retrieving any text from a web element or to enable a web element to get the text or to perform any action on it.
Let’s talk about JavaScript Executor in detail. It is an interface which helps to execute javascript.
JavaScript Executor
Sometimes you are not able to click on a web element using click() function. You can then use javascript executor to execute click function on a web element. Let’s have a look at the code.
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
You can now click on a webelement using below command.
WebElement button = driver.findElement(By.xpath(“”));
Js.executeScript(“arguments[0].click();”,button);
Also, if send keys isn’t working. You can make use of java script executor to send keys. Let’s look at the example below.
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“document.getElementById(‘id’).value=”value;”);
You can even make use of java script executor to refresh a web page. You can do it by following command:
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“history.go(0)”);
Sometimes, getText() doesn’t work and then you have to make use of java script executor to get text of a web element. You can do it by following line of code:
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“history.go(0)”);
Sysout(js.executeScript(“return document.documentElement.innerText;”).toString());
You can even get the title and URL of a web page using java script executor. The procedure is very simple. Let’s have a look at the following lines of code.
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
System.out.println(js.executeScript(“return document.title;”).toString());
System.out.println(js.executeScript(“return document.URL;”).toString());
Desired Capabilities Concept in selenium web driver
You can make the set of configurations on which you want a particular test script to run. You can pass browser name, version to specify the type of environment on which you want a test case to run.
Let’s see some of the capabilities which you can set in a test case for IE browser.
//it is used to define IE capability
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability(CapabilityType.BROWSER_NAME, “IE”);
cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
In the above capability, we have passed the capability browser name and we have ignored the security domain.
After setting the capabilities you can pass the capabilities to the web driver instance so that it executes the test on a particular configuration.
Let’s have a look at the complete set of code.
public static void main(String[] args) {
//it is used to define IE capability
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability(CapabilityType.BROWSER_NAME, “IE”);
cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
System.setProperty(“webdriver.ie.driver”, “path of executable”);
WebDriver driver = new InternetExplorerDriver(capabilities);
driver.get(“http://gmail.com”);
driver.quit();
}
Handling a drop down in selenium web driver
You have to first import following packages: org.openqa.selenium.support.ui.Select.
First, you have to identify from DOM whether the dropdown is of select type or not. If it is of select type then you have to go for the below steps.
Then, you have to uniquely identify the select tag. You have to first make the object of Select class and pass the element for which you have to choose the options from the drop-down.
Select dropdown = new Select(driver.findElement(By.xpath(“”)));
Now, there are three main methods which you have to use to select any element from this select object.

  1. selectByVisibleText
  2. selectByIndex
  3. selectByValue

You can either select any element from this drop-down by matching the visible text with that of the text passed by you. You can also select any web element from the drop-down using an index. Last option is to select by value tag.
Also, there are some more functions which are available. Some of them are selectAll() and deselectAll() too select and deselect all the elements when more than one element can be selected.
But, if the dropdown is not of select type then you can’t go for the conventional method. You have to follow another method. You have to uniquely identify the web element on which you have to select a dropdown option. You can identify it and the sendKeys() function of selenium web driver to send keys to the uniquely identified dropdown.
WebElement dropdown = driver.findElement(By.xpath(“”));
Dropdown.sendKeys(“value to be selected”);
How to select the checkbox and radio button is selenium
Sometimes, you come across situations where you have to select checkboxes and radio buttons. You can do it easily with selenium web driver. You just have to use click() function of web driver to click on checkbox and radio button. You can even check of the web element is selected or not.
.isSelected() checks if any web element is selected or not.
It gives false if the web element is not selected and it gives true if the web element is selected.
This way, you can handle radio buttons and checkboxes in a selenium script.

Selenium Advanced level Tutorial

Now, you know almost the stuff which is required for selenium intermediate and beginner level. Now, you are proficient enough to deal with all the advanced level of selenium web driver. You can then practice those and while you are done with those, you can move forward to the advanced level of course.
Let’s see what lies ahead and what can give you an edge in your interviews. You can look at this advanced course so that you can be ahead of all the candidates who just know the basic and intermediate selenium course. Let’s have a look at Selenium Advanced level Tutorial

Selenium Grid


Selenium Grid is issued for running various tests on different browsers, operating systems, and machines in parallel. It used a hub and node concept. You don’t want test cases to run on a single machine. You have your machine as a hub and various systems on which test cases will be distributed. You call those machines as nodes.
The hub is the central point and there should be only one hub in a system. This hub is your machine from which you want to distribute the test cases among all the clients.
This is the machine on which test cases will run and those will be executed on the nodes. There can be more than one node. Nodes can have different configurations with different platforms and browsers.
Let’s see how you can establish a selenium grid in your machine.
You can download the selenium grid server from the official site. You can place Selenium server.jar in a hard drive. You have to place it in all nodes and hub c drive.
Open the command prompt in your hub and then, go to C directory. There you have to fire the below command java -jar selenium-server-standalone-2.30.0.jar -role hub
Now, if you want to check if the selenium grid server is running on localhost that is 4040 port or not. You can visit the local host on your browser.
You have to then go to C directory of the node and open command prompt in it. Also, when you have made the selenium grid server up in the hub, you have to note down the IP address and port.
java -Dwebdriver.gecko.driver=”C:\geckodriver.exe” -jar selenium-server-standalone-3.4.0.jar -role webdriver -hub ip address of hub -port port number of hub
When you fire the above command, again go to hub browser and the port number 4040. Refresh the page and you will see IP address which will be linked to the hub.
Now, you have set up machines with different configurations. But how would the hub know which test case would be run on which node.
This will be done by desired capabilities which will tell that this test script would run on a particular set of configuration.
One can do it using below source code:
This way, you will be able to distribute the test cases across different machines and browsers. You will be able to do parallel testing using Selenium Grid.

Maven and Jenkins Integration with Selenium


Maven is a build management tool which is used to make the build process easy. Maven avoids hard coding of jars and you can easily share the project structure across the team using artifact and version id.
Every team member would be at the same page. You can make a maven project by going to File – New – Other – Maven project. You have to then specify the artifact id and then version id. You will be prompted to select a template. For starting, select a quik start template.
You will get a folder structure where you will be having two folders – src/main/java and src/main/test. In java folder, you will maintain all other stuff except tests while in test folder you will maintain all the test cases.
You will be having pom.xml file where you have to define all the dependencies so that it can download from the maven repository and place them in ./m2 repository in your local project structure.
You can get the dependency from the maven official site and then place in pom.xml. It will download all the required jars.
Also, Jenkins issued for continuous integration of the latest build with the production environment. Whenever a developer will fire the latest build then the smoke test will start running on that build.
If the build gets passed then it can be deployed to the production else the developer and tester would get a notification about the failed build. It makes the delivery cycle very fast.
Also, you can do it by downloading Jenkins war file and then running it so that Jenkins server will be up and running on port number 4040.

After doing that you can install all the necessary plug-ins. You can then create a new item and does the post-build actions.
Also, you can pass the path of git repository from which it will fetch the latest build. If you are using a local server then you pass the path of pom.xml from the system.
You can even set nightly runs with Jenkins, You have to specify the time when you want your test to run. They will run and you will get the reports on the Jenkins server the next morning. Isn’t it time-saving?

Database Testing using Selenium WebDriver

Integrating Selenium tests to the database is so easy in the latest version of the tool. You have to make use of JDBC library for database connections. It allows connection of Java and databases. First, make a connection to the database with the following command:

DriverManager.getConnection(URL, “userid”, “password” )
After doing that you can load the JDBC driver. You can do it by following lines of code:
Class.forName(“com.mysql.jdbc.Driver”);
Now, you have to send the query to the database. How will you do it? You can create an object of a statement class and then execute the query using the statement object.
Statement stmt = con.createStatement();
stmt.executeQuery(select *  from employee;);
Now, you can get the result in the result set. You can do it by following command:
ResultSet rs= stmt.executeQuery(query);
After doing all the operations, you can close the connection.
Con.close();
In this way, you can get the result set and then do all the validations on the result set.

How to take screenshots in selenium web driver

You should get the screenshot of the failed test cases so that you can get to know where exactly is the problem. This will help in better-debugging skills.

Let’s look at the steps involved in taking a screenshot:
TakesScreenshot scrShot =((TakesScreenshot)webdriver);
This step caste a driver instances to Takes Screenshot interface. Now, you have one method which is getting screenshots which will get the image file.
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
Now, you have taken the screenshot but you have to place it somewhere. You can create some folder which will be used for storing all the screenshots captured during the execution.
You can do it by following the line of code:
FileUtils.copyFile(SrcFile, DestFile);
This is the way to capture screenshots. But if you want that only the screenshot is taken when a test case fails. You can use ITestListener.
It has various methods and one of the methods is onFailure() which will do the specified task when every there is any failure in a test case.
So you can put this code in that method so that whenever any test fails it will take the screenshot and place it in the folder specified by you.

How to drag and drop in a web page using Selenium Web driver

Now if you want o drag and drop something o a web page, you would be confused. It is very simple. You have to make use of Actions class which gives you a method dragAndDrop() which will drag and drop a web element from a source destination to the desired destination.
Actions actions = new Actions(driver);
Actions. dragAndDrop(Sourcelocator, Destinationlocator).build().perform();
Make sure that the source locator and destination locator have correct xpaths. In this way, you will be able to drag and drop any element on a web page.

How to do right click and double click on a web page

You can do a right-click on a web page using Actions class. Actions class provides a doubleClick method which allows to double click on a web element. You can do it by following lines of code:

Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.id(“ID”));
actions.doubleClick(elementLocator).perform();
You have to do right-click in selenium using action class only. It is very easy. It provides a method – contextClick() and then right click on a web element.
Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.id(“ID”));
actions.contextClick(elementLocator).perform();
This way, you will be able to right click and double click on a web element.
How to switch to an iFrame

iFrame is a web page which is embedded into another web page. Whenever you want to click on a web element, which is in another iframe. First, you have to switch to that iframe and then perform an action on it.
You can do switching by
Driver.switchTo().frame(index or name or id of iframe);
Conclusion
Before learning Selenium it’s better to have a thorough understanding of any object-oriented language. languages that Selenium support includes, Java, Perl, C#,  PHP, Ruby, and Python Currently.
We genuinely hope this tutorial has helped in understanding selenium better.

Get a eBook : Download PDF

FitNesse Testing vs Selenium Testing, Which is Better & Why?

Programming and development of a software product is not an end of the entire task.
It is rather the beginning of the journey that concludes with the delivery of the best quality product.
Although, innovations and improvisations continue to occur even after the delivery, there is one step that certainly forms to be an integral part of all these steps – testing.
Testing or software testing is one such step that helps ensure that the product developed and delivered in the market is as per to the set quality standards.
It can be done in a number of ways based on the product’s requirements, type and other specifications.
Two of the most commonly used ones are FitNesse testing and Selenium testing.
FitNesse Testing
FitNesse is a commonly used and accepted testing framework that allows testers, developers and customers to join together to create the test cases.

This type of testing allows testers to use their preferred software’s functionality to create test cases.
The test cases created can then be documented in the form of testable code so as to run the tests as well as get results.
Comparing the actual functionality of the software with customer requirements makes it easier to ensure the delivery of better performing software.
The best aspect of this type of testing is that it can be used easily even by a non-technical professional.
The installation of FitNesse testing framework is easy. If required, one can also write and execute FitNesse tests via the browser.
This framework is available with its own version control and can be shared among multiple team members.
An active developer and user community make it easier to use this open source tool.
One can also design automated test cases that provide ease of maintenance. The framework is also highly flexible as it allows one to use other testing tools such as GUI drivers.
Selenium Testing
Selenium is a popular open-source web automation framework, which is used to test only web-based applications. This framework can record the inputs entered by the user and automating a web browser using a script code.

Also Read: Selenium 4: New Features and Updates

Selenium can be used easily by anyone who possesses a basic knowledge and understanding of Java or any other object-oriented language. This framework is capable of functioning across different web browsers and operating systems (OS).
Selenium consists of four major parts that include:

  1. Selenium Integrated Development Environment (IDE): Implemented as a Firefox extension, Selenium IDE allows the testers to record, test and debug the tests.
  2. Selenium Remote Control (RC): Capable of creating more complex tasks using programming languages such as Java, C# and PHP, Selenium RC allows the execution of more than simple browser actions.
  3. Selenium WebDriver: A substitute of Selenium RC, Selenium WebDriver sends the commands directly to the web browser as well as retrieve results. Selenium-WebDriver can better support dynamic web pages even when the elements of a particular page change without the page itself being reloaded.
  4. Selenium Grid: This is, in fact, the best tool available to execute testing in minimum span of time. Using Selenium Grid allows the testers to execute multiple tests in parallel across different machines and browsers, hence, in turn, resulting in minimum execution time.

Making a choice between FitNesse and Selenium Testing
Using FitNesse or Selenium framework is recommended in different scenarios.
One is advised to use Selenium framework for testing when the customers have not yet got involved in the testing process or the codes written can only be understood by the developer or tester engaged in writing the these cases.
FitNesse framework should be used when the individuals involved in automation testing have limited technical knowledge.
It should also be preferred over Selenium when the main focus is on creating such test cases that are easy to comprehend.
Some other situations when FitNesse should be used are when the team is on a lookout of receiving immediate feedback from end user or the test cases are to be presented in a user-friendly manner such as table.

At times, it is also recommended to use both the technologies in a combined manner. For instance, using FitNesse to present the data in tabular form and then, connecting the same to the Selenium using another bridge technology called Selenesse.
Conclusion
At the end, it is apt to say that there is no one framework that one should rely upon. While Selenium is suitable to be used for automating the web user interface, FitNesse allows one to create such test cases that can be easily understood by the customers.
There is no technology to rely upon as each of these is significant. Choosing the best on the basis of the current situation is what allows one to make the best use of these technologies.

How to Automate Mobile Application Testing Using Selenium

Selenium is an open-source testing tool that is primarily used for regression testing and functional testing. Identified as a collection of software testing tools, the Selenium suite can be used to automate web browser testing. Speaking of mobile application testing, it is a well-known fact that you as a tester must have heard about Selenium. And if you are curious to know whether Selenium can be used to automate mobile application testing, the following detailed explanation will throw light on your queries.
app testing
To answer the question “Can Selenium be a mobile application testing tool?” the answer is negative. But the good news is that you can make the most of the Selenium to test mobile websites. This is definitely a reason that can cheer you up. And there are a couple of another reasons that will make you smile.
Selenium, as an open-source testing tool, does not involve any licensing cost and hence ranks above over other testing tools that are currently employed. While you cannot use Selenium to automate mobile application testing, you are at an advantage to employ the frameworks of Selenium that are exclusively designed for mobile automated testing.
Selenium Frameworks Designed for Automating Mobile Application Testing

  1. Selendroid
  2. Appium

Selendroid:
In line with this very name, Selendroid is a Selenium framework that can be employed to test the user interface of native and hybrid applications that can be run on the Android platform. It is also important to note that while the Selendroid framework is suitable for emulators, it also can find its place in the Selenium Grid, when the framework can be integrated with real devices. Essentially meant to perform parallel testing and scaling, the Selendroid framework allows you to simultaneously communicate with multiple Android devices.
Selenium Appium: 
Selenium Appium is an automated, open source test framework that can be employed to test mobile user interfaces that come with native, hybrid and mobile web applications. It is also a cross-platform tool that can is compatible with many languages including Node.JS, PHP, Java, Objective-C, JavaScript, Clojure, C#, Python and Perl. You as a tester can make the most of its cross-platform characteristic when you can effortlessly employ Selenium Appium through a single test script to perform tests on Android, Windows, Mac, Linux or iOS platforms.
A Dozen Simple Steps Involved in Automating Mobile Application Testing Using Selenium Appium
1. Your first step is to visit http://appium.io. You then need to download the Appium framework along with sample files as demonstrated under:
appium-mobile-app-automation-screenshot
2. The next step is to unzip the downloaded files.
3. Proceed further by downloading and setting up Android-SDK file on to your computer.
4. Check out the Android-SDK framework and identify the AVD Manager application. This is to create a “Default”            Android Virtual Device.
5. The next step is to run Eclipse.
6. You then need to access the unzipped folder to import the Java->JUnit sample code according to the following              illustration.
import-screenshot
 
appium-master-screenshot
 
7. After the previous step, this is what you will get to see; the imported Java project structure.
src-screenshot
8. You are now all set to execute the Appium.exe file which is saved in the unzipped folder, as demonstrated below.
appium-desktop-screenshot
9. You can now launch the Appium server window that will show up as under.
appium-server-window-screenshot
10. Without any hassles, you can change the AndroidContactsTest.java file according to your requirements.
11. You can now run the Java class as JUnitTest as depicted below.
package-explorer-screenshot
12. Your outcome will be that the application has passed the test.
Voila! These simple steps when performed in series will grant you the power of Selenium Appium to automate mobile application testing.