Selenium Tutoria

Selenium Tutorial

Selenium is one of the automation testing tools which is an open source tool. Selenium automates web application. In this Free Selenium training tutorial, we cover all Selenium concepts (basic selenium scripts to advanced testing framework) in detail with easy to understand practical examples. This Selenium Tutorial is helpful for beginners to advanced level users who want to learn selenium or learn automation.

Why This Selenium WebDriver Tutorial?
In this Selenium Web Driver Tutorial, you will learn how to work with the selenium to create automated tests scripts (selenium scripts) for any Web Browser applications and how to create your own framework

Manual Testing Vs Automation Testing in Software Testing

We know that every project has three important aspects such as Quality, Cost & Time. The objective of any project is to get a high-quality output while controlling the cost and the time required for completing the project.

What is Software Testing?

But first, let’s clarify the term ‘Software Testing’.

Software testing is a process, to evaluate the functionality of a software application with an intent to find whether the developed software met the specified requirements or not and to identify the defects to ensure that the product is defect free in order to produce the quality product.

Check this ANSI/IEEE 1059 Standard Definition of Software Testing.

Software Testing is an integral part of any project.

Software testing is categorized into two areas namely Manual Testing & Automation Testing. Both manual testing and automation testing has their own advantages and disadvantages but it’s worth knowing the difference between manual & automation testing and when to you use manual testing and when to use automated testing.

What is Manual Testing?

Manual testing is the process of testing the software manually to find the defects. Tester should have the perspective of an end user and to ensure all the features are working as mentioned in the requirement document. In this process, testers execute the test cases and generate the reports manually without using any automation tools.

Types of Manual Testing:

Black Box Testing
White Box Testing
Unit Testing
System Testing
Integration Testing
Acceptance Testing

Black Box Testing: Black Box Testing is a software testing method in which testers evaluate the functionality of the software under test without looking at the internal code structure. This can be applied to every level of software testing such as Unit, Integration, System and Acceptance Testing.

White Box Testing: White Box Testing is also called as Glass Box, Clear Box, and Structural Testing. It is based on applications internal code structure. In white-box testing, an internal perspective of the system, as well as programming skills, are used to design test cases. This testing usually done at the unit level.

Unit Testing: Unit Testing is also called as Module Testing or Component Testing. It is done to check whether the individual unit or module of the source code is working properly. It is done by the developers in developer’s environment.

System Testing: Testing the fully integrated application to evaluate the systems compliance with its specified requirements is called System Testing AKA End to End testing. Verifying the completed system to ensure that the application works as intended or not.

Integration Testing: Integration Testing is the process of testing the interface between the two software units. Integration testing is done by three ways. Big Bang Approach, Top Down Approach, Bottom-Up Approach

Acceptance Testing: It is also known as pre-production testing.  This is done by the end users along with the testers to validate the functionality of the application. After successful acceptance testing. Formal testing conducted to determine whether an application is developed as per the requirement. It allows customer to accept or reject the application. Types of acceptance testing are Alpha, Beta & Gamma.

There are many types of software testing but here we dealt mainly about Manual and Automation Testing. Here you could read the complete list of software testing types.

When to use Manual Testing?

Exploratory Testing: Exploratory testing will be carried out by domain experts. They perform testing just by exploring the functionalities of the application without having the knowledge of the requirements.

Usability Testing: To verify whether the application is user-friendly or not and was comfortably used by an end user or not. The main focus in this testing is to check whether the end user can understand and operate the application easily or not. An application should be self-exploratory and must not require training to operate it.

Ad-hoc Testing: Ad-hoc testing is quite opposite to formal testing. It is an informal testing type. In Adhoc testing, testers randomly test the application without following any documents and test design techniques. This testing is primarily performed if the knowledge of testers in the application under test is very high. Testers randomly test the application without any test cases or any business requirement document.

When do you prefer Manual Testing over Automation Testing?

We prefer Manual Testing over Automation Testing in the following scenarios

When the project is in initial development stage.
When testing user interface especially their visual aspects.
When exploratory or adhoc testing needs to be performed.
If the project is a short term and writing scripts will be time consuming when compared to manual testing
If the test case is not automatable. Example captcha.
Manual Testing Pros and Cons

Advantages of Manual Testing:

Manual testing can be done on all kinds of applications
It is preferable for short life cycle products
Newly designed test cases should be executed manually
Application must be tested manually before it is automated
It is preferred in the projects where the requirements change frequently and for the products where the GUI changes constantly
It is cheaper in terms of initial investment compared to Automation testing
It requires less time and expense to begin productive manual testing
It allows tester to perform adhoc testing
There is no necessity to the tester to have knowledge on Automation Tools

Disadvantages of Manual Testing:

Manual Testing is time-consuming mainly while doing regression testing.
Manual testing is less reliable compared to automation testing because it is conducted by humans. So there will always be prone to errors and mistakes.
Expensive over automation testing in the long run

It is not possible to reuse because this process can’t be recorded

What is Automation Testing?

Automation testing is the process of testing the software using an automation tools to find the defects. In this process, executing the test scripts and generating the results are performed automatically by automation tools. Some most popular tools to do automation testing are HP QTP/UFT, Selenium WebDriver, etc.,

Some of the popular automation testing tools

HP QTP(Quick Test Professional)/UFT(Unified Functional Testing)
Selenium
LoadRunner
IBM Rational Functional Tester
SilkTest
TestComplete
WinRunner
WATIR
When to use Automation Testing?

We do Automation testing in the following areas:

Regression Testing: Repeated testing of an already tested program, after modification, to discover any defects introduced or uncovered as a result of the changes in the software being tested or in another related or unrelated software components. So, regression testing is best suitable for automated testing because of frequent code changes and it is beyond the human capacity to execute tests in a timely manner.

Read more about regression testing here

Load Testing:  It is to verify that the system/application can handle the expected number of transactions and to verify the system/application behavior under both normal and peak load conditions. Automated testing is also the best way to complete the testing efficiently when it comes to load testing. It is best suited for automation testing.

Read more about load testing here

Performance Testing – This type of testing determines or validates the speed, scalability, and/or stability characteristics of the system or application under test. Performance is concerned with achieving response times, throughput, and resource-utilization levels that meet the performance objectives for the project or product. It is best suited for automation testing.

Read more about load testing here

The tests which can be done through automated or manual approach:

Integration Testing – Integration Testing is the process of testing the interface between the two software units. Integration testing is done by multiple approaches such as Big Bang Approach, Top-Down Approach, Bottom-Up Approach, and Hybrid Integration approach.

Integration Testing Complete Guide

System Testing – Testing the fully integrated application to evaluate the system’s compliance with its specified requirements is called System Testing AKA End to End testing. Verifying the completed system to ensure that the application works as intended or not.

Unit Testing: Unit Testing is also called Module Testing or Component Testing. It is done to check whether the individual unit or module of the source code is working properly. It is done by the developers in the developer’s environment.

Acceptance Testing: It is also known as pre-production testing.  This is done by the end users along with the testers to validate the functionality of the application. After successful acceptance testing. Formal testing conducted to determine whether an application is developed as per the requirement. It allows the customer to accept or reject the application. Types of acceptance testing are Alpha, Beta & Gamma.

In interviews, you may be asked to answer the following question

Which tests cannot be automated?

Let’s see which tests cannot be automated. Test which take too much effort to automate are

Exploratory Testing
User interface testing
Adhoc Testing
When do you prefer Automation Testing over Manual Testing?

We prefer Manual Testing over Automation Testing in the following scenarios

To handle repetitive and time consuming tasks
To do parallel testing
To do non-functional testing like load, performance, stress testing
To avoid human errors
Automated Testing Pros and Cons

Advantages of automated testing:

Automation testing is faster in execution
It is cheaper compared to manual testing in a long run
Automated testing is more reliable
Automated testing is more powerful and versatile
It is mostly used for regression testing
It is reusable because automation process can be recorded
It does not require human intervention. Test scripts can be run unattended
It helps to increase the test coverage

Disadvantages of Automated Testing:

It is recommended only for stable products
Automation testing is expensive initially
Most of the automation tools are expensive
It has some limitations such as handling captcha, getting visual aspects of UI such as fonts, color, sizes etc.,
Huge maintenance in case of repeated changes in the requirements

Not all the tools support all kinds of testing. Such as windows, web, mobility, performance/load testing

Difference between Manual Testing & Automation Testing (Automation Testing Vs Manual Testing)?

Let’s see the difference between Manual Testing and Automation Testing.

Automation Testing Vs. Manual Testing:

Automation Testing Manual Testing
Automated testing is more reliable. It performs same operation each time. It eliminates the risk of human errors. Manual testing is less reliable. Due to human error, manual testing is not accurate all the time.
Initial investment of automation testing is higher. Investment is required for testing tools. In the long run it is less expensive than manual. ROI is higher in the long run compared to Manual testing. Initial investment of manual testing is less than automation. Investment is required for human resources. ROI is lower in the long run compared to Automation testing.
Automation testing is a practical option when we do regressions testing. Manual testing is a practical option where the test cases are not run repeatedly and only needs to run once or twice.
Execution is done through software tools, so it is faster than manual testing and needs less human resources compared to manual testing. Execution of test cases is time consuming and needs more human resources
Exploratory testing is not possible Exploratory testing is possible
Performance Testing like Load Testing, Stress Testing etc. is a practical option in automation testing. Performance Testing is not a practical option in manual testing
It can be done in parallel and reduce test execution time. Its not an easy task to execute test cases in parallel in manual testing. We need more human resources to do this and becomes more expensive.
Programming knowledge is a must in automation testing Programming knowledge is not required to do manual testing.
Build verification testing (BVT) is highly recommended Build verification testing (BVT) is not recommended
Human intervention is not much, so it is not effective to do User Interface testing. It involves human intervention, so it is highly effective to do User Interface testing.

Conclusion:

Here I am going to conclude this Manual Testing vs Automation Testing post. The real value of manual & automation testing comes when the right type of testing is applied in the right environment. Hope you have understood the difference between manual testing and automation testing and also learnt the advantages and disadvantages of both. If you find any other points which we overlooked, just put it in the comments. We will include and make this post “Manual Testing Vs Automation Testing” updated.

Automation Testing Vs Manual Testing | SoftwareTestingMaterial
What is Software Testing?

But first, let’s clarify the term ‘Software Testing’.

Software testing is a process, to evaluate the functionality of a software application with an intent to find whether the developed software met the specified requirements or not and to identify the defects to ensure that the product is defect free in order to produce the quality product.

Check this ANSI/IEEE 1059 Standard Definition of Software Testing.

Software Testing is an integral part of any project.

Software testing is categorized into two areas namely Manual Testing & Automation Testing. Both manual testing and automation testing has their own advantages and disadvantages but it’s worth knowing the difference between manual & automation testing and when to you use manual testing and when to use automated testing.

What is Manual Testing?

Manual testing is the process of testing the software manually to find the defects. Tester should have the perspective of an end user and to ensure all the features are working as mentioned in the requirement document. In this process, testers execute the test cases and generate the reports manually without using any automation tools.

Types of Manual Testing:

Black Box Testing
White Box Testing
Unit Testing
System Testing
Integration Testing
Acceptance Testing

Black Box Testing: Black Box Testing is a software testing method in which testers evaluate the functionality of the software under test without looking at the internal code structure. This can be applied to every level of software testing such as Unit, Integration, System and Acceptance Testing.

White Box Testing: White Box Testing is also called as Glass Box, Clear Box, and Structural Testing. It is based on applications internal code structure. In white-box testing, an internal perspective of the system, as well as programming skills, are used to design test cases. This testing usually done at the unit level.

Unit Testing: Unit Testing is also called as Module Testing or Component Testing. It is done to check whether the individual unit or module of the source code is working properly. It is done by the developers in developer’s environment.

System Testing: Testing the fully integrated application to evaluate the systems compliance with its specified requirements is called System Testing AKA End to End testing. Verifying the completed system to ensure that the application works as intended or not.

Integration Testing: Integration Testing is the process of testing the interface between the two software units. Integration testing is done by three ways. Big Bang Approach, Top Down Approach, Bottom-Up Approach

Acceptance Testing: It is also known as pre-production testing.  This is done by the end users along with the testers to validate the functionality of the application. After successful acceptance testing. Formal testing conducted to determine whether an application is developed as per the requirement. It allows customer to accept or reject the application. Types of acceptance testing are Alpha, Beta & Gamma.

There are many types of software testing but here we dealt mainly about Manual and Automation Testing. Here you could read the complete list of software testing types

When to use Manual Testing?

Exploratory Testing: Exploratory testing will be carried out by domain experts. They perform testing just by exploring the functionalities of the application without having the knowledge of the requirements.

Usability Testing: To verify whether the application is user-friendly or not and was comfortably used by an end user or not. The main focus in this testing is to check whether the end user can understand and operate the application easily or not. An application should be self-exploratory and must not require training to operate it.

Ad-hoc Testing: Ad-hoc testing is quite opposite to formal testing. It is an informal testing type. In Adhoc testing, testers randomly test the application without following any documents and test design techniques. This testing is primarily performed if the knowledge of testers in the application under test is very high. Testers randomly test the application without any test cases or any business requirement document.

When do you prefer Manual Testing over Automation Testing?

We prefer Manual Testing over Automation Testing in the following scenarios

When the project is in initial development stage.
When testing user interface especially their visual aspects.
When exploratory or adhoc testing needs to be performed.
If the project is a short term and writing scripts will be time consuming when compared to manual testing
If the test case is not automatable. Example captcha.
Manual Testing Pros and Cons

Advantages of Manual Testing:

Manual testing can be done on all kinds of applications
It is preferable for short life cycle products
Newly designed test cases should be executed manually
Application must be tested manually before it is automated
It is preferred in the projects where the requirements change frequently and for the products where the GUI changes constantly
It is cheaper in terms of initial investment compared to Automation testing
It requires less time and expense to begin productive manual testing
It allows tester to perform adhoc testing
There is no necessity to the tester to have knowledge on Automation Tools

Disadvantages of Manual Testing:

Manual Testing is time-consuming mainly while doing regression testing.
Manual testing is less reliable compared to automation testing because it is conducted by humans. So there will always be prone to errors and mistakes.
Expensive over automation testing in the long run

It is not possible to reuse because this process can’t be recorded

What is Automation Testing?

Automation testing is the process of testing the software using an automation tools to find the defects. In this process, executing the test scripts and generating the results are performed automatically by automation tools. Some most popular tools to do automation testing are HP QTP/UFT, Selenium WebDriver, etc.,

When to use Automation Testing?

We do Automation testing in the following areas:

Regression Testing: Repeated testing of an already tested program, after modification, to discover any defects introduced or uncovered as a result of the changes in the software being tested or in another related or unrelated software components. So, regression testing is best suitable for automated testing because of frequent code changes and it is beyond the human capacity to execute tests in a timely manner.

Load Testing:  It is to verify that the system/application can handle the expected number of transactions and to verify the system/application behavior under both normal and peak load conditions. Automated testing is also the best way to complete the testing efficiently when it comes to load testing. It is best suited for automation testing.

Performance Testing – This type of testing determines or validates the speed, scalability, and/or stability characteristics of the system or application under test. Performance is concerned with achieving response times, throughput, and resource-utilization levels that meet the performance objectives for the project or product. It is best suited for automation testing.

The tests which can be done through automated or manual approach:

Integration Testing – Integration Testing is the process of testing the interface between the two software units. Integration testing is done by multiple approaches such as Big Bang Approach, Top-Down Approach, Bottom-Up Approach, and Hybrid Integration approach.

Integration Testing Complete Guide

System Testing – Testing the fully integrated application to evaluate the system’s compliance with its specified requirements is called System Testing AKA End to End testing. Verifying the completed system to ensure that the application works as intended or not.

Unit Testing: Unit Testing is also called Module Testing or Component Testing. It is done to check whether the individual unit or module of the source code is working properly. It is done by the developers in the developer’s environment.

Acceptance Testing: It is also known as pre-production testing.  This is done by the end users along with the testers to validate the functionality of the application. After successful acceptance testing. Formal testing conducted to determine whether an application is developed as per the requirement. It allows the customer to accept or reject the application. Types of acceptance testing are Alpha, Beta & Gamma.

In interviews, you may be asked to answer the following question

Which tests cannot be automated?

Let’s see which tests cannot be automated. Test which take too much effort to automate are

Exploratory Testing
User interface testing
Adhoc Testing
When do you prefer Automation Testing over Manual Testing?

We prefer Manual Testing over Automation Testing in the following scenarios

To handle repetitive and time consuming tasks
To do parallel testing
To do non-functional testing like load, performance, stress testing
To avoid human errors
Automated Testing Pros and Cons

Advantages of automated testing:

Automation testing is faster in execution
It is cheaper compared to manual testing in a long run
Automated testing is more reliable
Automated testing is more powerful and versatile
It is mostly used for regression testing
It is reusable because automation process can be recorded
It does not require human intervention. Test scripts can be run unattended
It helps to increase the test coverage

Disadvantages of Automated Testing:

It is recommended only for stable products
Automation testing is expensive initially
Most of the automation tools are expensive
It has some limitations such as handling captcha, getting visual aspects of UI such as fonts, color, sizes etc.,
Huge maintenance in case of repeated changes in the requirements

Not all the tools support all kinds of testing. Such as windows, web, mobility, performance/load testing

Difference between Manual Testing & Automation Testing (Automation Testing Vs Manual Testing)?

Let’s see the difference between Manual Testing and Automation Testing.

Automation Testing Vs. Manual Testing:

Automation Testing Manual Testing
Automated testing is more reliable. It performs same operation each time. It eliminates the risk of human errors. Manual testing is less reliable. Due to human error, manual testing is not accurate all the time.
Initial investment of automation testing is higher. Investment is required for testing tools. In the long run it is less expensive than manual. ROI is higher in the long run compared to Manual testing. Initial investment of manual testing is less than automation. Investment is required for human resources. ROI is lower in the long run compared to Automation testing.
Automation testing is a practical option when we do regressions testing. Manual testing is a practical option where the test cases are not run repeatedly and only needs to run once or twice.
Execution is done through software tools, so it is faster than manual testing and needs less human resources compared to manual testing. Execution of test cases is time consuming and needs more human resources
Exploratory testing is not possible Exploratory testing is possible
Performance Testing like Load Testing, Stress Testing etc. is a practical option in automation testing. Performance Testing is not a practical option in manual testing
It can be done in parallel and reduce test execution time. Its not an easy task to execute test cases in parallel in manual testing. We need more human resources to do this and becomes more expensive.
Programming knowledge is a must in automation testing Programming knowledge is not required to do manual testing.
Build verification testing (BVT) is highly recommended Build verification testing (BVT) is not recommended
Human intervention is not much, so it is not effective to do User Interface testing. It involves human intervention, so it is highly effective to do User Interface testing.

Conclusion:

Here I am going to conclude this Manual Testing vs Automation Testing post. The real value of manual & automation testing comes when the right type of testing is applied in the right environment. Hope you have understood the difference between manual testing and automation testing and also learnt the advantages and disadvantages of both. If you find any other points which we overlooked, just put it in the comments. We will include and make this post “Manual Testing Vs Automation Testing” updated.

Manual Testing Vs Automation Testing in Software Testing
What is Software Testing?

But first, let’s clarify the term ‘Software Testing’.

Software testing is a process, to evaluate the functionality of a software application with an intent to find whether the developed software met the specified requirements or not and to identify the defects to ensure that the product is defect free in order to produce the quality product.

Software Testing is an integral part of any project.

Software testing is categorized into two areas namely Manual Testing & Automation Testing. Both manual testing and automation testing has their own advantages and disadvantages but it’s worth knowing the difference between manual & automation testing and when to you use manual testing and when to use automated testing.

First, we will see what is Manual testing & Automation Testing.

What is Manual Testing?

Manual testing is the process of testing the software manually to find the defects. Tester should have the perspective of an end user and to ensure all the features are working as mentioned in the requirement document. In this process, testers execute the test cases and generate the reports manually without using any automation tools.

Types of Manual Testing:

Black Box Testing
White Box Testing
Unit Testing
System Testing
Integration Testing
Acceptance Testing

Black Box Testing: Black Box Testing is a software testing method in which testers evaluate the functionality of the software under test without looking at the internal code structure. This can be applied to every level of software testing such as Unit, Integration, System and Acceptance Testing.

White Box Testing: White Box Testing is also called as Glass Box, Clear Box, and Structural Testing. It is based on applications internal code structure. In white-box testing, an internal perspective of the system, as well as programming skills, are used to design test cases. This testing usually done at the unit level.

Unit Testing: Unit Testing is also called as Module Testing or Component Testing. It is done to check whether the individual unit or module of the source code is working properly. It is done by the developers in developer’s environment.

System Testing: Testing the fully integrated application to evaluate the systems compliance with its specified requirements is called System Testing AKA End to End testing. Verifying the completed system to ensure that the application works as intended or not.

Integration Testing: Integration Testing is the process of testing the interface between the two software units. Integration testing is done by three ways. Big Bang Approach, Top Down Approach, Bottom-Up Approach

Acceptance Testing: It is also known as pre-production testing.  This is done by the end users along with the testers to validate the functionality of the application. After successful acceptance testing. Formal testing conducted to determine whether an application is developed as per the requirement. It allows customer to accept or reject the application. Types of acceptance testing are Alpha, Beta & Gamma.

There are many types of software testing but here we dealt mainly about Manual and Automation Testing. Here you could read the complete list of software testing types.

When to use Manual Testing?

Exploratory Testing: Exploratory testing will be carried out by domain experts. They perform testing just by exploring the functionalities of the application without having the knowledge of the requirements.

Usability Testing: To verify whether the application is user-friendly or not and was comfortably used by an end user or not. The main focus in this testing is to check whether the end user can understand and operate the application easily or not. An application should be self-exploratory and must not require training to operate it.

Ad-hoc Testing: Ad-hoc testing is quite opposite to formal testing. It is an informal testing type. In Adhoc testing, testers randomly test the application without following any documents and test design techniques. This testing is primarily performed if the knowledge of testers in the application under test is very high. Testers randomly test the application without any test cases or any business requirement document.

When do you prefer Manual Testing over Automation Testing?

We prefer Manual Testing over Automation Testing in the following scenarios

When the project is in initial development stage.
When testing user interface especially their visual aspects.
When exploratory or adhoc testing needs to be performed.
If the project is a short term and writing scripts will be time consuming when compared to manual testing
If the test case is not automatable. Example captcha.
Manual Testing Pros and Cons

Advantages of Manual Testing:

Manual testing can be done on all kinds of applications
It is preferable for short life cycle products
Newly designed test cases should be executed manually
Application must be tested manually before it is automated
It is preferred in the projects where the requirements change frequently and for the products where the GUI changes constantly
It is cheaper in terms of initial investment compared to Automation testing
It requires less time and expense to begin productive manual testing
It allows tester to perform adhoc testing
There is no necessity to the tester to have knowledge on Automation Tools

Disadvantages of Manual Testing:

Manual Testing is time-consuming mainly while doing regression testing.
Manual testing is less reliable compared to automation testing because it is conducted by humans. So there will always be prone to errors and mistakes.
Expensive over automation testing in the long run

It is not possible to reuse because this process can’t be recorded

What is Automation Testing?

Automation testing is the process of testing the software using an automation tools to find the defects. In this process, executing the test scripts and generating the results are performed automatically by automation tools. Some most popular tools to do automation testing are HP QTP/UFT, Selenium WebDriver, etc.,

Some of the popular automation testing tools

HP QTP(Quick Test Professional)/UFT(Unified Functional Testing)
Selenium
LoadRunner
IBM Rational Functional Tester
SilkTest
TestComplete
WinRunner
WATIR
When to use Automation Testing?

We do Automation testing in the following areas:

Regression Testing: Repeated testing of an already tested program, after modification, to discover any defects introduced or uncovered as a result of the changes in the software being tested or in another related or unrelated software components. So, regression testing is best suitable for automated testing because of frequent code changes and it is beyond the human capacity to execute tests in a timely manner.

Load Testing:  It is to verify that the system/application can handle the expected number of transactions and to verify the system/application behavior under both normal and peak load conditions. Automated testing is also the best way to complete the testing efficiently when it comes to load testing. It is best suited for automation testing.

Performance Testing – This type of testing determines or validates the speed, scalability, and/or stability characteristics of the system or application under test. Performance is concerned with achieving response times, throughput, and resource-utilization levels that meet the performance objectives for the project or product. It is best suited for automation testing.

The tests which can be done through automated or manual approach:

Integration Testing – Integration Testing is the process of testing the interface between the two software units. Integration testing is done by multiple approaches such as Big Bang Approach, Top-Down Approach, Bottom-Up Approach, and Hybrid Integration approach.

Integration Testing Complete Guide

System Testing – Testing the fully integrated application to evaluate the system’s compliance with its specified requirements is called System Testing AKA End to End testing. Verifying the completed system to ensure that the application works as intended or not.

Unit Testing: Unit Testing is also called Module Testing or Component Testing. It is done to check whether the individual unit or module of the source code is working properly. It is done by the developers in the developer’s environment.

Acceptance Testing: It is also known as pre-production testing.  This is done by the end users along with the testers to validate the functionality of the application. After successful acceptance testing. Formal testing conducted to determine whether an application is developed as per the requirement. It allows the customer to accept or reject the application. Types of acceptance testing are Alpha, Beta & Gamma.

In interviews, you may be asked to answer the following question

Which tests cannot be automated?

Let’s see which tests cannot be automated. Test which take too much effort to automate are

Exploratory Testing
User interface testing
Adhoc Testing
When do you prefer Automation Testing over Manual Testing?

We prefer Manual Testing over Automation Testing in the following scenarios

To handle repetitive and time consuming tasks
To do parallel testing
To do non-functional testing like load, performance, stress testing
To avoid human errors
Automated Testing Pros and Cons

Advantages of automated testing:

Automation testing is faster in execution
It is cheaper compared to manual testing in a long run
Automated testing is more reliable
Automated testing is more powerful and versatile
It is mostly used for regression testing
It is reusable because automation process can be recorded
It does not require human intervention. Test scripts can be run unattended
It helps to increase the test coverage

Disadvantages of Automated Testing:

It is recommended only for stable products
Automation testing is expensive initially
Most of the automation tools are expensive
It has some limitations such as handling captcha, getting visual aspects of UI such as fonts, color, sizes etc.,
Huge maintenance in case of repeated changes in the requirements

Not all the tools support all kinds of testing. Such as windows, web, mobility, performance/load testing

Difference between Manual Testing & Automation Testing (Automation Testing Vs Manual Testing)?

Let’s see the difference between Manual Testing and Automation Testing.

Automation Testing Vs. Manual Testing:

Automation Testing Manual Testing
Automated testing is more reliable. It performs same operation each time. It eliminates the risk of human errors. Manual testing is less reliable. Due to human error, manual testing is not accurate all the time.
Initial investment of automation testing is higher. Investment is required for testing tools. In the long run it is less expensive than manual. ROI is higher in the long run compared to Manual testing. Initial investment of manual testing is less than automation. Investment is required for human resources. ROI is lower in the long run compared to Automation testing.
Automation testing is a practical option when we do regressions testing. Manual testing is a practical option where the test cases are not run repeatedly and only needs to run once or twice.
Execution is done through software tools, so it is faster than manual testing and needs less human resources compared to manual testing. Execution of test cases is time consuming and needs more human resources
Exploratory testing is not possible Exploratory testing is possible
Performance Testing like Load Testing, Stress Testing etc. is a practical option in automation testing. Performance Testing is not a practical option in manual testing
It can be done in parallel and reduce test execution time. Its not an easy task to execute test cases in parallel in manual testing. We need more human resources to do this and becomes more expensive.
Programming knowledge is a must in automation testing Programming knowledge is not required to do manual testing.
Build verification testing (BVT) is highly recommended Build verification testing (BVT) is not recommended
Human intervention is not much, so it is not effective to do User Interface testing. It involves human intervention, so it is highly effective to do User Interface testing.

Conclusion:

Here I am going to conclude this Manual Testing vs Automation Testing post. The real value of manual & automation testing comes when the right type of testing is applied in the right environment. Hope you have understood the difference between manual testing and automation testing and also learnt the advantages and disadvantages of both. If you find any other points which we overlooked, just put it in the comments. We will include and make this post “Manual Testing Vs Automation Testing” updated.

Selenium Introduction – IDE, RC, WebDriver and Grid
Selenium Introduction:

Selenium Introduction – It is an open source (free) automated testing suite to test web applications. It supports different platforms and browsers. It has gained a lot of popularity in terms of web-based automated testing and giving a great competition to the famous commercial tool HP QTP (Quick Test Professional) AKA HP UFT (Unified Functional Testing).

Selenium is a set of different software tools. Each tool has a different approach in supporting web based automation testing.

It has four components namely,
i. Selenium IDE (Integrated Development Environment)
ii. Selenium RC (Remote Control)
iii. Selenium WebDriver
iv. Selenium Grid

QTP is a famous automation tool and it was originally developed by Mercury Interactive before HP acquired it. Selenium is used as an antidote in the treatment of mercury intoxication. Jason Huggins (An engineer at ThoughtWorks – the one who introduced Selenium tool) suggested the name of this automation tool as Selenium.

What is Selenium IDE?

Selenium IDE (Integrated Development Environment) is a Firefox plugin. It is the simplest framework in the Selenium Suite. It allows us to record and playback the scripts. Even though we can create scripts using Selenium IDE, we need to use Selenium RC or Selenium WebDriver to write more advanced and robust test cases.

Operation System Support – Windows, Mac OS, Linux
Browser Support – Mozilla Firefox

What is Selenium RC?

Selenium RC AKA Selenium 1. Selenium RC was the main Selenium project for a long time before the WebDriver merge brought up Selenium 2. Selenium 1 is still actively supported (in maintenance mode). It relies on JavaScript for automation. It supports Java, Javascript, Ruby, PHP, Python, Perl and C#. It supports almost every browser out there.

Operation System Support – Windows, Mac OS, Linux, Solaris
Browser Support – Mozilla Firefox, Internet Explorer, Google Chrome, Safari, Opera

What is Selenium WebDriver?

Selenium WebDriver AKA Selenium 2 is a browser automation framework that accepts commands and sends them to a browser. It is implemented through a browser-specific driver. It controls the browser by directly communicating with it. Selenium WebDriver supports Java, C#, PHP, Python, Perl, Ruby.

Operation System Support – Windows, Mac OS, Linux, Solaris
Browser Support – Mozilla Firefox, Internet Explorer, Google Chrome 12.0.712.0 and above, Safari, Opera 11.5 and above, Android, iOS, HtmlUnit 2.9 and above

What is Selenium Grid?

Selenium Grid is a tool used together with Selenium RC to run tests on different machines against different browsers in parallel. That is, running multiple tests at the same time against different machines running different browsers and operating systems.

How To Install Selenium IDE, Fire Bug, Fire Path

Before going through how to install Selenium IDE, Fire Bug, Fire Path. Let’s look into in the pre-requisities we need to install Selenium IDE, Fire Bug, Fire Path.

We need to have the following
i. Mozilla Firefox
ii. Active Internet Connection

Download and Install Selenium IDE, Fire Bug, Fire Path

Follow the below steps to complete the installation.

Step 1: Download and Install Selenium IDE
Step 2: Download and Install Fire Bug
Step 3: Download and Install Fire Path

Please be patient. The video will load in some time.

Step 1: Download and Install Selenium IDE

Open Mozilla firefox and go to the below mentioned link

1

http://docs.seleniumhq.org/download/

Under Selenium IDE section, click on the link as shown in the below pic.

Now you could see Selenium IDE by navigating through

Tools – Selenium IDE or by typing Ctrl+Alt+S

Step 2: Download and Install Fire Bug

Go to the link mentioned below to install Fire Bug

1

https://addons.mozilla.org/en-US/firefox/addon/firebug/

Now you could see Fire Bug by navigating through

Tools – Web Developer – Firebug – Open Firebug (or) use shortcut key ‘F12’

Step 3: Download and Install Fire Path

Final step is to install Fire Bug. To do this, go to the link mentioned below to install Fire Path

1

https://addons.mozilla.org/en-US/firefox/addon/firepath/

Click on Add to Firefox button

Click on Install button

Click on Restart Now

Now you could see Fire Path by navigating through

Tools – Web Developer – Firebug – Open Firebug (or) use shortcut key ‘F12’

You could find the ‘XPath’ by using ‘FirePath’ as shown below

Selenium WebDriver Architecture | Software Testing Material
Selenium WebDriver Architecture

In this post, we see Selenium WebDriver Architecture in detail. Architecture of Selenium WebDriver is all about how Selenium works internally. We know Selenium is a browser automation tool which interacts with browser and automate end to end tests of a web application.

Don’t Miss: Selenium Tutorial – Learn Step By Step

Selenium is a suite of tools. It consists of Selenium IDE, Selenium RC, Selenium Webdriver, and Selenium Grid

Why WebDriver driver = new FirefoxDriver();

Selenium IDE:

Selenium IDE (Integrated Development Environment) is a Firefox plugin. It is the simplest framework in the Selenium Suite. It allows us to record and playback the scripts. Even though we can create scripts using Selenium IDE, we need to use Selenium RC or Selenium WebDriver to write more advanced and robust test cases.

How to Install Selenium IDE

Selenium RC:

Selenium RC AKA Selenium 1. Selenium RC was the main Selenium project for a long time before the WebDriver merge brought up Selenium 2. Selenium 1 is still actively supported (in maintenance mode). It relies on JavaScript for automation. It supports Java, Javascript, Ruby, PHP, Python, Perl and C#. It supports almost every browser out there.

Note: Selenium RC is officially deprecated.

Selenium WebDriver:

Selenium WebDriver is a browser automation framework that accepts commands and sends them to a browser. It is implemented through a browser-specific driver. It controls the browser by directly communicating with it. Selenium WebDriver supports Java, C#, PHP, Python, Perl, Ruby.

Operation System Support – Windows, Mac OS, Linux, Solaris
Browser Support – Mozilla Firefox, Internet Explorer, Google Chrome 12.0.712.0 and above, Safari, Opera 11.5 and above, Android, iOS, HtmlUnit 2.9 and above

How to Install Selenium WebDriver

Selenium Grid:

Selenium Grid is a tool used together with Selenium RC to run tests on different machines against different browsers in parallel. That is, running multiple tests at the same time against different machines running different browsers and operating systems.

Selenium WebDriver is a well designed object oriented API supports many languages such as Java, C#, Python etc. Let’s see what is API and then we move on to know the complete picture of Selenium WebDriver Architecture.

API:

Application Programming Interface (API) works as an interface between various software components.

Learn API Testing in 10 mins

Selenium WebDriver API:

Selenium Webdriver API helps in communication between languages and browsers. Selenium supports many programming languages such as Java, C#, Python etc., and also it supports multiple browsers such as Google Chrome, Firefox, Internet Explorer etc.,

Real Time Selenium WebDriver Interview Questions

Every browser has different logic of performing actions like loading a page, closing the browser etc.

Here is the Selenium WebDriver Framework Architecture Diagram

Selenium WebDriver Architecture

There are four components of Selenium Architecture:

Selenium Client Library
JSON Wire Protocol over HTTP
Browser Drivers
Browsers

Must Read: Top TestNG Interview Questions

Selenium Client Libraries/Language Bindings:

Selenium supports multiple libraries such as Java, Ruby, Python, etc., Selenium Developers have developed language bindings to allow Selenium to support multiple languages. Check out Selenium Libraries in the official site.

JSON WIRE PROTOCOL Over HTTP Client:

JSON stands for JavaScript Object Notation. It is used to transfer data between a server and a client on the web. JSON Wire Protocol is a REST API that transfers the information between HTTP server. Each BrowserDriver (such as FirefoxDriver, ChromeDriver etc.,)  has its own HTTP server.

Browser Drivers:

Each browser contains separate browser driver. Browser drivers communicate with respective browser without revealing the internal logic of browser’s functionality. When a browser driver is  received any command then that command will be executed on the respective browser and the response will go back in the form of HTTP response..

Browsers:

Selenium supports multipe browsers such as Firefox, Chrome, IE, Safari etc.,

Let’s see how Selenium WebDriver works internally

In real time, you write a code in your UI (say Eclipse IDE) using any one of the supported Selenium client libraries (say Java).

Example:

1
2

WebDriver driver  = new FirefoxDriver();
driver.get(https://www.softwaretestingmaterial.com)

Once you are ready with your script, you will click on Run to execute the program. Based on the above statements, Firefox browser will be launched and it will navigates to softwartestingmaterial website.

Here we see what will happen internally after you click on Run till the launch of Firefox browser.

Once you click on Run, every statement in your script will be converted as a URL with the help of JSON Wire Protocol over HTTP. The URL’s will be passed to the Browser Drivers. (In the above code, we took FirefoxDriver). Here in our case the client library (java) will convert the statements of the script to JSON format and communicates with the FirefoxDriver. URL looks as shown below.

1

http://localhost:8080/{“url”:”https://www.softwaretestingmaterial.com”}

Every Browser Driver uses a HTTP server to receive HTTP requests.  Once the URL reaches the Browser Driver, then the Browser Driver will pass that request to the real browser over HTTP. Then the commands in your selenium script will be executed on the browser.

If the request is POST request then there will be an action on browser

If the request is a GET request then the corresponding response will be generated at the browser end and it will be sent over HTTP to the browser driver and the Browser Driver over JSON Wire Protocol and sends it to the UI (Eclipse IDE).

How To Download And Install Selenium WebDriver (2020)

Before going through how to install Selenium WebDriver. Let’s look into in the pre-requisities we need to install Selenium WebDriver.

We need to have the following
i. Mozilla Firefox
ii. Active Internet Connection

Download Selenium and Install Selenium WebDriver

Follow the below steps to complete the installation.

Step 1: Download and Install JAVA
Step 2: Download and Install Eclipse
Step 3: Download and Install FireBug
Step 4: Download and Install FirePath
Step 5: Download Selenium WebDriver

Java version – 10.0.1
Eclipse – Photon
Selenium WebDriver – 3.13.0

Please be patient. The video will load in some time.

Step 1: Download and Install JAVA

Check below video to see “How To Install Java”

Go to the below mentioned link and download latest version of JAVA or click here

1

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Accept the license agreement and choose the right ‘JDK’ file to download based on your system requirement.

Once downloaded. Go ahead and verify the Java version. To do this, open command prompt and type “java -version” and hit enter

Step 2: Download and Install Eclipse

Go to the following link to download eclipse

1

http://www.eclipse.org/downloads/

Download the appropriate file based on your system requirement

Download ‘Eclipse IDE for Java Developers’

Extract the eclipse file which you have downloaded

Right click on ‘eclipse.exe’ and run it as ‘Run as administrator’

Choose specified path to create ‘workspace’ by using ‘Browse’ button.

You could create Java Projects, Packages and Classes in Java Eclipse.

Step 3. Download and Install FireBug

Go to the link mentioned below to install Fire Bug

1

https://addons.mozilla.org/en-US/firefox/addon/firebug/

Click on Add to Firefox button

Click on Install button

Now you could see Fire Bug by navigating through

Tools – Web Developer – Firebug – Open Firebug (or) use shortcut key ‘F12’

Step 4: Download and Install FirePath

Go to the link mentioned below to install Fire Path

1

https://addons.mozilla.org/en-US/firefox/addon/firepath/

Click on Add to Firefox button

Click on Install button

Click on Restart Now

Now you could see Fire Path by navigating through

Tools – Web Developer – Firebug – Open Firebug (or) use shortcut key ‘F12’

You could find the ‘XPath’ by using ‘FirePath’ as shown below

Step 5: Download and Install Selenium WebDriver

Go to the following link to download latest Selenium Java jars (latest Selenium WebDriver jars).

1

http://www.seleniumhq.org/download/

Extract the Selenium file

Open Eclipse and Create Java Project:

File – New – Java Project

Add project name and click on Next followed by Finish.

Create a Package:

Right click on the project you have created and select New – Package

Enter name of the package and click on Finish

Right click on the project you have created and select New – Class

Enter name of the class and click on Finish

Now right click on the newly created project and select ‘Properties’ – ‘Java Build Path’

Select Libraries Tab and click on ‘Add External Jars’

Select all the jars files as shown in the below images and click on Open

Now you could start your first Selenium WebDriver Program.

Top 7 Challenges in Test Automation {Challenges & Limitations in Selenium WebDriver}
Challenges and limitations of Selenium WebDriver

As we all know Selenium WebDriver is a tool which automates the browser to mimic real user actions on the web. Selenium is a free open source testing tool. Some of the challenges with Selenium WebDriver are as follows

1. We cannot test windows application:

Selenium doesn’t support windows based applications. It supports only web-based applications.

2. We cannot test mobile apps:

We can test on any operating system and browser on the desktop using selenium but we cant deal mobile testing with selenium alone. But there is a solution for this. You can use Appium to handle iOS and Android native, mobile, and hybrid apps using the WebDriver protocol.

3. Limited reporting:

With selenium, you couldn’t generate a good report. But there is a workaround. You can generate reports using TestNG or Extent reports.

4. Handling dynamic Elements:

Some of the web elements are dynamic in nature. If an element’s id is changing on every page load then it bit tricky to handle this in the normal way. We need to handle the dynamic elements with dynamic xpath or dynamic css selectors. Functions like starts-with, contains, ends with, etc., works well to handle dynamic objects.

5. Handling page load:

Some of the web pages are user specific. These user-specific pages load different elements depends on the different user. Sometimes some elements appear depends upon the previous action. If you choose a country from country dropdown then cities related that country will load in the cities dropdown. In runtime selenium script may not identify the element. To overcome this we need to use explicit waits in the script to give the elements enough time to load and to identify the element.

6. Handling pop up windows:

Windows-based pops are part of the operating system. It’s beyond selenium’s capabilities. We could use AutoIT to handle the windows based popups.

7. Handling captcha:

Handling captcha is a limitation in selenium. There are some third-party tools to automate captcha but still, we cannot achieve 100% results.

First Selenium WebDriver Script | Selenium Tutorial
Creating First Selenium WebDriver Script:

Here I don’t want to go in depth to show the first Selenium WebDriver script. I would like to keep it very simple.

Hope you have already installed Selenium WebDriver. If not go through the below mentioned link to download and install Selenium WebDriver.

How To Download And Install Selenium WebDriver

In the first Selenium WebDriver Script, let’s see the below mentioned sceanario using Selenium WebDriver.

Scenario:
To open appropriate URL and verify the title of the home page

Steps:
i. Open Firefox browser
ii. Go to the specified URL
iii. Verify the title and print the output of the title
iv. Close the Firefox browser

Test Data:
URL: https://www.softwaretestingmaterial.com
Expected Value: Software Testing Material – A site for Software Testers

To create our first Selenium WebDriver Script, we have to first create a Java Project, Package and Class in Eclipse.

i. Create a Java Project “SoftwareTestingMaterial”
ii. Create a package “seleniumTutorial”
iii. Create a Java Class “FirstSeleniumWebDriverScript”

Test script with an explanation:

(Note: We use // text when we want to comment a single line of code. and use /* text */ when we want to comment multiple lines of code)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

package seleniumTutorial;

//Importing packages
//We need to import relevant packages depends on our needs.
import org.openqa.selenium.WebDriver;
//It contains the WebDriver class to instantiate a new browser
import org.openqa.selenium.firefox.FirefoxDriver;
//It contains the FirefoxDriver class to instantiate a Firefox driver

public class FirstSeleniumWebDriverScript {

public static void main(String[] args) {
System.setProperty(“webdriver.gecko.driver”,”D://Selenium Training//Selenium Environment Files//geckodriver.exe”);
//Instantiation of driver object. To launch Firefox browser
WebDriver driver = new FirefoxDriver();
//Declaration of variables
String url = “http://softwaretestingmaterial.com”;
String expectedTitle = “Software Testing Material – A site for Software Testers”;
String actualTitle = null;

//To oepn URL “http://softwaretestingmaterial.com”. This is what we have assigned to the variable named ‘url’.
driver.get(url);
//To get the actual value of the title. getTitle method used to get the page title
actualTitle = driver.getTitle();
//Using if-else condition to compare the Expected Title and Actual Title. As per the below lines of code (if-else condition).
if (actualTitle.contentEquals(expectedTitle)){
//’system.out.println’ prints the output
System.out.println(“Expected Value is “+expectedTitle);
System.out.println(“Actual Value is “+actualTitle);
System.out.println(“Test Passed”);
} else {
System.out.println(“Expected Value is “+expectedTitle);
System.out.println(“Actual Value is “+actualTitle);
System.out.println(“Test Failed”);
}
//’close’ method is used to close the browser window
driver.close();
//To run the script – Go to menu bar – click on Run – Run or use shortcut key Ctrl+F11
//You could see the output in the console as shown below:
//Expected Value is Software Testing Material – A site for Software Testers
//Actual Value is Software Testing Material – A site for Software Testers
//Test Passed
}
}

Check out the below link for the complete list of Selenium WebDriver tutorials. There is a propaganda in the industry as learning and working on Selenium is very difficult. To be frank, learning Selenium is very easy.

Selenium WebDriver Tutorial

If you are not regular reader of my blog then I highly recommend you to sign up for the free email newsletter using the below link.

Gecko Driver – Launching Firefox Browser In Selenium 3

Gecko Driver – Launching Firefox Browser In Selenium 3:

Selenium WebDriver scripts which were working fine yesterday are not working today?

Why it is not working? Every Selenium Tester has this question. The solution is here. We need to have Gecko Driver to run our scripts with the updated Selenium.

Executing Selenium WebDriver Script in Firefox Browser using Gecko Driver:

Here in this post, we see how to run Selenium WebDriver Script in Firefox Browser using Gecko Driver. Moving forward, we need to have geckodriver.exe and Selenium WebDriver.

Please be patient. The video will load in some time.

Assuming that you have already Installed Selenium WebDriver.

If you want to install Selenium WebDriver, click on the link below to install Selenium WebDriver in few clicks.

How To Download And Install Selenium WebDriver

Each and every browser has its own Driver to execute Selenium WebDriver Scripts. Selenium WebDriver supports browsers such as Mozilla Firefox, Google Chrome, Internet Explorer, Opera, Safari etc.,

Here we are going to see how to run Selenium WebDriver Script in Firefox Browser using Gecko Driver.

Why Gecko Driver?

Selenium has launched Selenium 3 and if you are using Firefox latest version then you may face some issues.

To launch latest version of Firefox Browser using Selnium 3, we need to set a system property “webdriver.gecko.driver” to the path of executable file “geckodriver.exe”

Also find,

How to Run Selenium Webdriver Script in Firefox browser – Old Version
How to Run Selenium Webdriver Script in Internet Explorer
How to Run Selenium WebDriver Script in Chrome Browser

Now, let’s see step by step process

Step 1: Download GeckoDriver.exe

Download the latest release of Gecko driver and unzip the downloaded compressed file and keep it somewhere on a known location on your system.

Step 2: Executing the Test Script in Firefox Browser

Find the sample script (using Java) mentioned below to run test script in Firefox browser using Gecko Driver. Execute it to run the test in Firefox browser which will first open Firefox browser and then open the appropriate URL mentioned in the script

SCRIPT:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

package seleniumTutorial;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GeckoDriver {

public static void main(String[] args) {

//Change the path based on your file path
//System.setProperty(“webdriver.gecko.driver”,”Path of geckodriver.exe”)

System.setProperty(“webdriver.gecko.driver”,”D://Selenium Training//Selenium Environment Files//geckodriver.exe”);

WebDriver driver = new FirefoxDriver();

driver.get(“https://www.softwaretestingmaterial.com/software-testing-interview-questions-free-ebook/”);

System.out.println(“Selenium Webdriver Script in Firefox browser using Gecko Driver | Software Testing Material”);

driver.close();

}

}

Common Issues You May Face:

Issue 1:

If you use old version of mozilla firefox (eg. firefox 45) and latest version of Selenium (Selenium 3.0.1) then you face the below mentioned error.

Exception in thread “main” java.lang.IllegalStateException

Issue 2:

If you use latest version of Mozilla Firefox (eg. Firefox 49) and old version of Selenium (Selenium 2.53) then you face the below mentioned error.

Solution – Failed To Launch IE Driver Using Selenium WebDriver
Failed To Launch IE Driver Using Selenium WebDriver?

I heard from many Selenium WebDriver users that they failed to launch IE driver using Selenium WebDriver. Here are the solutions for the common issues most of us might have faced.

Earlier, we have seen “How to Run Selenium WebDriver Script in Internet Explorer browser“. Perhaps, we may failed to launch IE driver using Selenium WebDriver. Error might be similar to the one which we placed in the below screenshot.

Error 1: Exception in thread “main” org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information).

Solution: To fix this error, we need to enable protected mode for all zones.

Follow the below steps to enable protected mode for all zones.

Open Internet Explorer
Go to Tools menu – Internet Options
Select Security Tab
In Select a zone to view or change security settings choose Internet and select the check box of Enable protected mode (requires restarting Internet Explorer).
Similarly, select the check box of Enable protected mode (requires restarting Internet Explorer) for other three such as Local Intranet, Trusted sites, and Restricted sites.

Error 2 : Exception in thread “main” org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Browser zoom level was set to 200%. It should be set to 100% (WARNING: The server did not provide any stacktrace information).

Solution: To fix this error, we need to set Zoom level of Internet Explorer browser to 100%

Follow the below steps to set Zoom level to 100%

Open Internet Explorer
To to View – Zoom – Select 100%

Do you want to try running the Selenium WebDriver script in Google Chrome. To run the quick start click on the below link.

How to Run Selenium WebDriver Script in Chrome browser

Find the sample script (using Java) mentioned below to run test script in Chrome browser. Execute it to run the test in Chrome browser which will first open chrome browser and then open the appropriate URL mentioned in the script

Quick note:

To launch Chrome Browser, we have to do as mentioned below:

1. Set a system property “webdriver.chrome.driver” to the path of executable file “Chromedriver.exe“. If you miss this, you will face an error “The path to the driver executable must be set by the webdriver.chrome.driver system property“.

2. Instantiate a ChromeDriver class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

package seleniumTutorial;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

public class ChormeBrowserScript {

public static void main(String [] args) throws InterruptedException{
//System.setProperty(“webdriver.chrome.driver”,path of executable file “Chromedriver.exe”)
System.setProperty(“webdriver.chrome.driver”, “D:/SeleniumEnvironment/chromedriver_win32/chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.get(“https://www.softwaretestingmaterial.com/software-testing-interview-questions-free-ebook/”);
System.out.println(“Selenium Webdriver Script in Chrome browser | Software Testing Material”);
driver.close();
}
}

How to Run Selenium WebDriver Script in Internet Explorer browser
Executing Selenium WebDriver Script in Internet Explorer Browser:

Here in this post, we see how to run Selenium WebDriver Script in Internet Explorer Browser. Moving forward, we need to have IEDriverServer.exe and Selenium WebDriver.

Assuming that you have already Installed Selenium WebDriver.

If you want to install Selenium WebDriver, click on the link below to install Selenium WebDriver in few clicks.

How To Download And Install Selenium WebDriver

Each and every browser has its own Driver to execute Selenium WebDriver Scripts. Selenium WebDriver supports browsers such as Mozilla Firefox, Google Chrome, Internet Explorer, Opera, Safari etc.,

Here we are going to see how to run Selenium WebDriver Script in Internet Explorer Browser.

What is IEDriver and What it does?

The InternetExplorerDriver is a standalone server which implements WebDriver’s wire protocol. It is a separate executable that WebDriver uses to control Internet Explorer. This executable starts a server on local system to run the Selenium WebDriver Test Scripts.

Also find,

How to Run Selenium Webdriver Script in Chorme browser
How to Run Selenium Webdriver Script in Firefox browser

Steps to run Selenium WebDriver Script in Internet Explorer Browser

Step 1: Download IEDriverServer.exe

Click here to download Internet Explorer driver

Download the latest release of Internet Explorer driver which is compatible to your test environment. Unzip the downloaded compressed file and keep it somewhere on a known location on your system.

Step 2: Executing the Test Script in Internet Explorer Browser

Find the sample script (using Java) mentioned below to run test script in Internet Explorer browser. Execute it to run the test in Internet Explorer browser which will first open Internet Explorer browser and then open the appropriate URL mentioned in the script

Quick note:

To launch Internet Explorer Browser, we have to do as mentioned below:

1. Set a system property “webdriver.ie.driver” to the path of executable file “IEDriverServer.exe“. If you miss this, you will face an error “The path to the driver executable must be set by the webdriver.ie.driver system property“.

2. Instantiate a Internet Explorer Driver class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

package rules;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.ie.InternetExplorerDriver;

public class stmtest {

public static void main(String [] args) throws InterruptedException{
//System.setProperty(“webdriver.ie.driver”,path of executable file “IEDriverServer.exe”)
System.setProperty(“webdriver.ie.driver”, “D://Selenium Environment//IEDriverServer_x64_2.53.1//IEDriverServer.exe”);
//Initialize InternetExplorerDriver Instance.
WebDriver driver = new InternetExplorerDriver();
driver.get(“https://www.softwaretestingmaterial.com/software-testing-interview-questions-free-ebook/”);
System.out.println(“Selenium Webdriver Script in Internet Explorer browser | Software Testing Material”);
driver.close();
}
}

In this process of launching IE browser using Selenium WebDriver, you may face few errors. Click on the link below to find the solutions for some of the common errors.

Difference Between FindElement And FindElements Methods

To automate a web application using Selenium WebDriver, we need to locate the elements on a web page. We use different locators depends on our needs to find the elements. Here is a link to the post “Locators in Selenium“. In this post, we discuss two methods to find the elements on a webpage namely findElement and findElements methods.

Let’s see the detailed overview – difference between findElement and findElements methods.

The difference between findElement and findElements methods:

FINDELEMENT() METHOD:

findElement method is used to access a single web element on a page. It returns the first matching element. It throws a NoSuchElementException exception when it fails to find If the element.

Syntax:

1

driver.findElement(By.xpath(“Value of Xpath”));

FINDELEMENTS() METHOD:

findElements method returns the list of all matching elements. The findElement method throws a NoSuchElementException exception when the element is not available on the page. Whereas, the findElements method returns  an empty list when the element is not available or doesn’t exist on the page. It doesn’t throw NoSuchElementException.

Syntax:

1

List link = driver.findElements(By.xpath(“Value of Xpath”));

Let’s see a practical example – FindElement and FindElements methods in Selenium WebDriver:

FindElement method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

package seleniumTutorial;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FindelementFindElements {
public static void main (String [] args){
// Open browser
WebDriver driver = new FirefoxDriver();
// To maximize the window
driver.manage.window.maximize();
// Open Application
driver.get(“https://www.google.co.in/?gws_rd=ssl#q=softwaretestingmaterial.com”);
// Get text of a particular link
String FindElement = driver.findElement(By.xpath(“//*[@id=’rso’]/div[1]/div/div/h3/a”)).getText();
// Print the value of the link
System.out.println(FindElement);
// Click on the link
driver.findElement(By.xpath(“//*[@id=’rso’]/div[1]/div/div/h3/a”)).click();
}
}

FindElements method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

package seleniumTutorial;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FindelementFindElements {
public static void main (String [] args){
// Open browser
WebDriver driver = new FirefoxDriver();
// To maximize the window
driver.manage().window().maximize();
// Open application
driver.get(“https://www.google.co.in/?gws_rd=ssl#q=softwaretestingmaterial.com”);
// Get the list of all links
List link = driver.findElements(By.xpath(“//*[@id=’rso’]/div/div/div/h3/a”));
// Using for loop to display the text of all the links
for(WebElement element:link)
{
System.out.println(element.getText());
}
// Click on the first link
driver.findElement(By.xpath(“//*[@id=’rso’]/div/div/div/h3/a”)).click();
}
}

How To Install Selenium IDE, Fire Bug, Fire Path

Before going through how to install Selenium IDE, Fire Bug, Fire Path. Let’s look into in the pre-requisities we need to install Selenium IDE, Fire Bug, Fire Path.

We need to have the following
i. Mozilla Firefox
ii. Active Internet Connection

Download and Install Selenium IDE, Fire Bug, Fire Path

Follow the below steps to complete the installation.

Step 1: Download and Install Selenium IDE
Step 2: Download and Install Fire Bug
Step 3: Download and Install Fire Path

Please be patient. The video will load in some time.

Step 1: Download and Install Selenium IDE

Open Mozilla firefox and go to the below mentioned link

1

http://docs.seleniumhq.org/download/

Under Selenium IDE section, click on the link as shown in the below pic.

Click on Add to Firefox button

Click on Install button

Click on Restart Now

Now you could see Selenium IDE by navigating through

Tools – Selenium IDE or by typing Ctrl+Alt+S

Step 2: Download and Install Fire Bug

Go to the link mentioned below to install Fire Bug

1

https://addons.mozilla.org/en-US/firefox/addon/firebug/

Click on Add to Firefox button

Click on Install button

Now you could see Fire Bug by navigating through

Tools – Web Developer – Firebug – Open Firebug (or) use shortcut key ‘F12’

Step 3: Download and Install Fire Path

Final step is to install Fire Bug. To do this, go to the link mentioned below to install Fire Path

1

https://addons.mozilla.org/en-US/firefox/addon/firepath/

Click on Add to Firefox button

Click on Install button

Click on Restart Now

Now you could see Fire Path by navigating through

Tools – Web Developer – Firebug – Open Firebug (or) use shortcut key ‘F12’

You could find the ‘XPath’ by using ‘FirePath’ as shown below.

Locators in Selenium WebDriver | Selenium Tutorial

Locators in Selenium – Before going ahead, I assume you have already gone through the installation of FireBug and FirePath. If not, check out the link mentioned below:

How To Install Fire Bug, Fire Path

We use FireBug and FirePath to identify the Locators in Selenium

Hope you have already installed Selenium WebDriver. If not go through the below mentioned link to download and install Selenium WebDriver.

How To Download And Install Selenium WebDriver

Selenium identifies the elements to be worked on using the following locators.

Different types of Locators in Selenium are as follows:

i. ID
ii. Name
iii. Class Name
iv. Tag Name
v. Link Text & Partial Link Text
vi. CSS Selector
vii. XPath

Locating elements in WebDriver is done by using the method “findElement(By.locator())“.

We use above mentioned method to locate elements but the locator() part will be replaced with the locator names. Mentioned few examples below for reference.

1
2

findElement(By.id(“IdName”))
findElement(By.className(“ClassName”))

Here is the link to the post “Difference between findElement and findElements methods”

Let’s see each of the Locators in Selenium in detail:

ID Locator:

ID’s are unique for each element so it is common way to locate elements using ID Locator. As per W3C, ID’s are supposed to be unique on a page and it makes ID’s are the most reliable locator. ID locators are the fastest and safest locators out of all locators.

id = id of the element

1

findElement(By.id(“IdName”))

Click this link for detailed explanation of ID Locator

Name Locator:

We sometimes use Name locator to identify the elements on our webpage. Locating elements using Name is same as locating elements using ID locator.

These are not unique on a page. If there are multiple elements with the same Name locator then the first element on the page is selected. Test may fail, if another element with the same Name locator is present on the web page or added by the developers in the later stages.

Name = Name of the element

1

findElement(By.name(“Name”))

Click this link for detailed explanation of Name Locator

Class Name Locator:

Class Name locator gives the element which matches the values specified in the attribute name “class”.

1

findElement(By.className(“Element Class”))

Click this link for detailed explanation of Class Name Locator

Tag Name Locator:

Tag Name locator is used to find the elements matching the specified Tag Name. It is very helpful when we want to extract the content within a Tag.

1

findElement(By.tagName(“HTML Tag Name”))

Click this link for detailed explanation of Tag Name Locator

Link Text Locator:

If there are multiple elements with the same link text then the first one will be selected. This Link Text locator works only on links (hyperlinks) so it is called as Link Text locator.

1

findElement(By.linkText(“LinkText”))

Click this link for detailed explanation of Link Text Locator

Partial Link Text:

In some situations, we may need to find links by a portion of the text in a Link Text element. it contains. In such situations, we use Partial Link Text to locate elements.

1

findElement(By.partialLinkText(“partialLinkText”))

Click this link for detailed explanation of Partial Link Text Locator

CSS Selector Locator:

There is a debate on the performance between CSS Locator and XPath locator and the debate on the performance of CSS and XPath locator is out of scope of this post. Most of the automation testers believe that using CSS selector makes the execution of script faster compared to XPath locator. This locator is always the best way to locate elements on the page.

Following are the some of the mainly used formats of CSS Selectors.

Tag and ID

1

findElement(By.cssSelector(tag#id))
Tag and Class

1

findElement(By.cssSelector(tag.class))
Tag and Attribute

1

findElement(By.cssSelector(tag[attribute=value]))
Tag, Class and Attribute

1

findElement(By.cssSelector(tag.class[attribute=value]))

Click this link for detailed explanation of CSS Selector Locator

XPath Locator:

XPath is designed to allow the navigation of XML documents, with the purpose of selecting individual elements, attributes, or some other part of an XML document for specific processing. XPath produces reliable locators but in performance wise it is slower (especially in IE older versions) compared to CSS Selector.

How To Write Dynamic XPath In Selenium WebDriver | Software Testing Material
How To Write Dynamic XPath In Selenium:

Before learning how to write dynamic XPath in Selenium, we will learn what is XPath locator.

XPath Locator:

XPath is designed to allow the navigation of XML documents, with the purpose of selecting individual elements, attributes, or some other part of an XML document for specific processing. XPath produces reliable locators but in performance wise it is slower (especially in IE older versions) compared to CSS Selector.

Syntax:

1

findElement(By.xpath(“XPath”));

Sometimes, we may not identify the element using the locators such as id, class, name, etc. In those cases, we use XPath to find an element on the web page. Check this link to identify the xpath using firepath plugin. At times, XPath may change dynamically and we need to handle the elements while writing scripts. Standard way of writing xpath may not work and we need to write dynamic XPath in selenium scripts. Let’s see different way of writing dynamic XPath in Selenium with examples:

Using Single Slash
Using Double Slash
Using Single Attribute
Using Multiple Attribute
Using AND
Using OR
Using contains()
Using starts_with()
Using text()
Using last()
Using position()
Using index()
Using following xpath axes
Using preceding xpath axes

Learn How To Write Dynamic CSS Selector In Selenium WebDriver [Without Any Tool]

Here is a video tutorial to learn “Creating dynamic XPath in Selenium WebDriver”:

Please be patient. The video will load in some time.

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

Here I am trying to find the element (Email field) on Gmail Login Page

HTML Code: (Gmail login page – Email field)

1
2

<input id=”Email” type=”email” <span class=”html-attribute-name”>value</span>=”” <span class=”html-attribute-name”>spellcheck</span>=”<span class=”html-attribute-value”>false</span>” class=”emailClass”
autofocus=”” <span class=”html-attribute-name”>name</span>=”<span class=”html-attribute-value”>Email</span>” placeholder=”Enter your email”/>

1. Using Single Slash:

This mechanism is also known as finding elements using Absolute XPath.

Single slash is used to create XPath with absolute path i.e. the XPath would be created to start selection from the document node/start node/parent node.

Syntax:

1

html/body/div[1]/div[2]/div[2]/div[1]/form/div[1]/div/div[1]/div/div/input[1]

2. Double Slash:

This mechanism is also known as finding elements using Relative XPath.

Double slash is used to create XPath with relative path i.e. the XPath would be created to start selection from anywhere within the document. – Search in a whole page (DOM) for the preceding string

Syntax:

1

//form/div[1]/div/div[1]/div/div/input[1]

3. Single Attribute:

You could write the syntax in two ways as mentioned below. Including or excluding HTML Tag. If you want to exclude HTML Tag then you need to use *

Syntax:

1
2
3
4
5

//<HTML tag>[@attribute_name=’attribute_value’]

or

//*[@attribute_name=’attribute_value’]

Note: ‘*‘ after double slash is to match any tag with the desired text

XPath based on above HTML:

1
2
3
4
5

//input[@id=’Email’]

or

//*[@id=’Email’]

4. Multiple Attribute:

Syntax:

1
2
3
4
5

//<HTML tag>[@attribute_name1=’attribute_value1′][@attribute_name2=’attribute_value2]

or

//*[@attribute_name1=’attribute_value1′][@attribute_name2=’attribute_value2]

XPath based on above HTML:

1
2
3
4
5

//input[@id=’Email’][@name=’Email’]

or

//*[@id=’Email’][@name=’Email’]

5. Using AND

Syntax:

1
2
3
4
5

//<HTML tag>[@attribute_name1=’attribute_value1′ and @attribute_name2=’attribute_value2]

or

//*[@attribute_name1=’attribute_value1′ and @attribute_name2=’attribute_value2]

XPath based on above HTML:

1
2
3
4
5

//input[@id=’Email’ and @name=’Email’]

or

//*[@id=’Email’ and @name=’Email’]

6. Using OR:

Syntax:

1
2
3
4
5

//<HTML tag>[@attribute_name1=’attribute_value1′ or @attribute_name2=’attribute_value2]

or

//*[@attribute_name1=’attribute_value1′ or @attribute_name2=’attribute_value2]

XPath based on above HTML:

1
2
3
4
5

//input[@id=’Email’ or @name=’Email’]

or

//*[@id=’Email’ or @name=’Email’]

7. contains(): It is used to identify an element, when we are familiar with some part of the attributes value of an element.

Syntax:

1
2
3
4
5

//<HTML tag>[contains(@attribute_name,’attribute_value’)]

or

//*[contains(@attribute_name,’attribute_value’)]

XPath based on above HTML:

1
2
3
4
5
6
7
8
9
10
11
12
13

//input[contains(@id,’Email’)]

or

//*[contains(@id,’Email’)]

or

//input[contains(@name,’Email’)]

or

//*input[contains(@name,’Email’)]

8. starts-with(): It is used to identify an element, when we are familiar with the attributes value (starting with the specified text) of an element.

Syntax:

1
2
3
4
5

//<HTML tag>[starts-with(@attribute_name,’attribute_value’)]

or

//*[starts-with(@attribute_name,’attribute_value’)]

XPath based on above HTML:

1
2
3
4
5

//input[starts-with(@id,’Ema’)]

or

//*[starts-with(@id,’Ema’)]

9. text(): This mechanism is used to locate an element based on the text available on a webpage

As per the above image, we could identify the elements text based on the below xpath.

1

//*[text()=’New look for sign-in coming soon’]

10. last(): Selects the last element (of mentioned type) out of all input element present

To identify the element (last text field ) “Your current email address”, we could use the below xpath.

1

findElement(By.xpath(“(//input[@type=’text’])[last()]”))

To identify the element “Year”, we could use the below xpath.

[last()-1] – Selects the last but one element (of mentioned type) out of all input element present

1

findElement(By.xpath(“(//input[@type=’text’])[last()-1]”))

11. position(): Selects the element out of all input element present depending on the position number provided

In below given xpath, [@type=’text’] will locate text field and function [position()=2] will locate text filed which is located on 2nd position from the top.

1
2
3
4
5
6

findElement(By.xpath(“(//input[@type=’text’])[position()=2]”))

or

findElement(By.xpath(“(//input[@type=’text’])[2]”))

12. Finding elements using index

By providing the index position in the square brackets, we could move to the nth element. Based on the below xpath, we could identify the Last Name field.

1

findElement(By.xpath(“//label[2]”))

13. following: By using this we could select everything on the web page after the closing tag of the current node

xpath of the FirstName field is as follows

1

//*[@id=’FirstName’]

To identify the input field of type text after the FirstName field, we need to use the below xpath.

1

//*[@id=’FirstName’]/following::input[@type=’text’]

Here I used, following xpath axes and two colons and then specified the required tag (i.e., input)

To identify just the input field after the FirstName field, we need to use the below xpath.

1

//*[@id=’FirstName’]/following::input

14. preceding: Selects all nodes that appear before the current node in the document, except ancestors, attribute nodes and namespace nodes

xpath of the LastName field is as follows

1

//*[@id=’LastName’]

To identify the input field of type text before the LastName field, we need to use the below xpath.

1

//*[@id=’LastName’]//preceding::input[@type=’text’]”

Here I used, preceding xpath axes and two colons and then specified the required tag (i.e., input).

If you have any queries, please comment below in the comment section. Like this post? Don’t forget to share it!

Learn CSS Selector Selenium WebDriver Tutorial [Without Using Any Tools]
CSS Selectors Locator:

There is a debate on the performance of CSS Locator and XPath locator and the debate on the performance of CSS and XPath locator is out of scope of this post. Most of the automation testers believe that using CSS selectors makes the execution of script faster compared to XPath locator. CSS Selector locator is always the best way to locate elements on the page. CSS is always same irrespective of browsers. In this post, I will show you how to find element locators using CSS without using any tools like Firebug or Firepath.

Must Read: How To Write Dynamic XPath in Selenium WebDriver

img: CSS Selector Selenium WebDriver Tutorial

Following are some of the mainly used formats of CSS Selectors.

Tag and ID
Tag and Class
Tag and Attribute
Tag, Class, and Attribute
Sub-String Matches
Starts With (^)
Ends With ($)
Contains (*)
Child Elements
Direct Child
Sub-child
nth-child

Refer to W3C CSS-Selectors for a list of generally available CSS Selectors

Tag and ID:

CSS ID Selector.

Syntax:

1

css=tag#id

Open Mozilla Firefox and navigate to Gmail application.

Open Firebug and inspect the Enter your email input box. Take a note of its Tag and ID. Follow the below screenshot to do so.

Copy the below mentioned script and execute in your system.

1
2
3
4

<div>
<label class=”hidden-label” for=”Email”> Enter your email</label>
<input id=”Email” type=”email” autofocus=”” placeholder=”Enter your email” name=”Email” spellcheck=”false” value=””> <input id=”Passwd-hidden” class=”hidden” type=”password” spellcheck=”false”>
</div>

Value to be added in the By.cssSelector method:

1

css=input#Email

Script:

1
2
3
4
5
6
7
8
9
10
11
12

package seleniumTutorial;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Locators {
public static void main (String [] args){
WebDriver driver = new FirefoxDriver();
driver.get(“https://www.gmail.com”);
// Here Tag = input and Id = Email
driver.findElement(By.cssSelector(“input#Email”)).sendKeys(“Software Testing Material”);
}
}
Tag and Class:

If multiple elements have the same HTML tag and class, then the first one will be recognized.

Syntax:

1

css=tag.class

Open Mozilla Firefox and navigate to Facebook application.

Open Firebug and inspect the Email input box. Take a note of its Tag and Class. Follow the below screenshot to do so.

Copy the below mentioned script and execute in your system.

1
2
3

<td>
<input id=”email“ class=”inputtext“ type=”email“ tabindex=”1“ value=”” name=”email“>
</td>

Value to be added in the By.cssSelector method:

1

css=input.inputtext

Script:

1
2
3
4
5
6
7
8
9
10
11
12

package seleniumTutorial;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Locators {
public static void main (String [] args){
WebDriver driver = new FirefoxDriver();
driver.get(“https://www.facebook.com/”);
// Here Tag = input and Class = email
driver.findElement(By.cssSelector(“input.inputtext”)).sendKeys(“Software Testing Material”);
}
}
Tag and Attribute:

If multiple elements have the same HTML tag and attribute, then the first one will be recognized. It acts in the same way of locating elements using CSS selectors with the same tag and class.

Syntax:

1

css=tag[attribute=value]

Open Mozilla Firefox and navigate to Gmail application.

Open Firebug and inspect the Enter your email input box. Take a note of its Tag and Attribute. Follow the below screenshot to do so.

Copy the below mentioned script and execute in your system.

1
2
3
4

<div>
<label class=”hidden-label“ for=”Email“> Enter your email</label>
<input id=”Email“ type=”email“ autofocus=”” placeholder=”Enter your email“ name=”Email“ spellcheck=”false“ value=””> <input id=”Passwd-hidden“ class=”hidden“ type=”password“ spellcheck=”false“>
</div>

Value to be added in the By.cssSelector method:

1

css=input[name=Email]
Script:

1
2
3
4
5
6
7
8
9
10
11
12

package seleniumTutorial;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Locators {
public static void main (String [] args){
WebDriver driver = new FirefoxDriver();
driver.get(“https://www.gmail.com”);
// Here Tag = input and Id = Email
driver.findElement(By.cssSelector(“input[name=Email]”)).sendKeys(“Software Testing Material”);
}
}
Tag, Class And Attribute:

Syntax:

1

css=tag.class[attribute=value]

Open Mozilla Firefox and navigate to Facebook application.

Open Firebug and inspect the Email input box. Take a note of its Tag, Class and Attribute. Follow the below screenshot to do so.

Copy the below mentioned script and execute in your system.

1
2
3

<td>
<input id=”email” class=”inputtext” type=”email” tabindex=”1″ value=”” name=”email”>
</td>

Value to be added in the By.cssSelector method:

1

css=input.inputtext[name=email]

Script:

1
2
3
4
5
6
7
8
9
10
11
12

package seleniumTutorial;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Locators {
public static void main (String [] args){
WebDriver driver = new FirefoxDriver();
driver.get(“https://www.facebook.com/”);
// Here Tag = input and Class = email
driver.findElement(By.cssSelector(“input.inputtext[name=email]”)).sendKeys(“Software Testing Material”);
}
}
SUB-STRING MATCHES:

CSS in Selenium has an interesting feature of allowing partial string matches using ^, $, and *.

Have a look on the below mentioned HTML

1

<input=”Employee_ID_001″>
Starts with (^):

To select the element, we would use ^ which means ‘starts with’

Syntax:

1

css=<HTML tag><[attribute^=prefix of the string]>

Value to be added in the By.cssSelector method:

1

css=input[id^=’Em’]

Add the below step in the script to find the element and write a text as “hi”

1

driver.findElement(By.cssSelector(“input[id^=’Em’]”)).sendKeys(“hi”);
Ends with ($):

To select the element, we would use $ which means ‘ends with’

Syntax:

1

css=<HTML tag><[attribute$=suffix of the string]>

Value to be added in the By.cssSelector method:

1

css=input[id$=’001′]

Add the below step in the script to find the element and write a text as “hi”

1

driver.findElement(By.cssSelector(“input[id$=’001′]”)).sendKeys(“hi”);
Contains (*):

To select the element, we would use * which means ‘sub-string’

Syntax:

1

css=<HTML tag><[attribute*=sub string]>

Value to be added in the By.cssSelector method:

1

css=input[id*=’id’]

Add the below step in the script to find the element and write a text as “hi”

1

driver.findElement(By.cssSelector(“input[id*=’id’]”)).sendKeys(“hi”);
Also we can use ‘contains()’:
1

driver.findElement(By.cssSelector(“input:contains(‘id’)”)).sendKeys(“hi”);
Locating Child Elements(Direct Child):
1
2
3

<div id=”buttonDiv” class=”small”>
<button id=”submitButton” type=”button” class=”btn”>Submit</button>
</div>

Syntax: parentLocator>childLocator

CSS Locator: div#buttonDiv>button

Explanation: ‘div#buttonDiv>button’ will first go to div element with id ‘buttonDiv’ and then select its child element – ‘button’

Locating elements inside other elements (child or sub-child):

Syntax: parentLocator>locator1 locator2

CSS Locator: div#buttonDiv button

Explanation: ‘div#buttonDiv button’ will first go to div element with id ‘buttonDiv’ and then select ‘button’ element inside it (which may be its child or sub child)

Locating nth Child:

To find nth-child css.

1
2
3
4
5

<ul id=”automation”>
<li>Selenium</li>
<li>QTP</li>
<li>Sikuli</li>
</ul>

To locate the element with text ‘QTP’, we have to use “nth-of-type”

1

css=”ul#automation li:nth-of-type(2)”

Similarly, To select the last child element, i.e. ‘Sikuli’, we can use

1

css=”ul#automation li:last-child”

If you have any queries by finding elements using CSS Selector Selenium, please comment below in the comment section. Like this post? Don’t forget to share it!

How To Handle Drop Down And Multi Select List Using Selenium WebDriver
Handle Drop Down And Multi Select List Using Selenium WebDriver:

To handle drop down and multi select list using Selenium WebDriver, we need to use Select class.

The Select class is a Webdriver class which provides the implementation of the HTML SELECT tag. It exposes several “Select By” and “Deselect By” type methods. We use these methods to select or deselect in the drop down list or multi select object. The Select class is the part of the selenium package.

We need to import the below mentioned library.

1

import org.openqa.selenium.support.ui.Select;

Standard syntax of Select Class is as follows:

1

Select dropdown = new Select(<WebElement>);

Example:

1
2

WebElement mySelectElement = driver.findElement(By.name(“dropdown”));
Select dropdown = new Select(mySelectElement);

or

1

Select dropdown = new Select(driver.findElement(By.xpath(“//select[@name=’dropdown’]”)));

Note: The Select class starts with capital ‘S’.

To Handle Drop Down And Multi Select List in Selenium we use the following types of Select Methods.

Types of Select Methods:

i. selectByVisibleText Method
ii. selectByIndex Method
iii. selectByValue Method

Types of DeSelect Methods:
i. deselectByVisibleText Method
ii. deselectByIndex Method
iii. deselectByValue Method
iv. deselectAll Method

Let’s see one by one with a sample program:

SelectByVisibleText Method:

It works based on the ‘visible text‘ provided by us.

Syntax:

1

dropdown.selectByVisibleText();

Sample program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

package softwareTestingMaterial;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class SelectMethod {

@Test
public static void captureScreenMethod() throws Exception{
System.setProperty(“webdriver.chrome.driver”,”D://Selenium Environment//Drivers//chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“https://www.softwaretestingmaterial.com/sample-webpage-to-automate/”);
driver.navigate().refresh();
//Once you got the select object initialised then you can access all the methods of select class.
//Identify the select HTML element:
Thread.sleep(10000);
WebElement mySelectElement = driver.findElement(By.name(“dropdown”));
Select dropdown= new Select(mySelectElement);
//To select an option – selectByVisibleText, selectByIndex, selectByValue
//selectByVisibleText
dropdown.selectByVisibleText(“Automation Testing”);
}
}

SelectByIndex Method:

It works based on the ‘index value‘ provided by us.

Syntax:

1

dropdown.selectByIndex(Index);

Sample program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

package softwareTestingMaterial;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class SelectMethod {

@Test
public static void captureScreenMethod() throws Exception{
System.setProperty(“webdriver.chrome.driver”,”D://Selenium Environment//Drivers//chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“https://www.softwaretestingmaterial.com/sample-webpage-to-automate/”);
driver.navigate().refresh();
//Once you got the select object initialised then you can access all the methods of select class.
//Identify the select HTML element:
Thread.sleep(10000);
WebElement mySelectElement = driver.findElement(By.name(“dropdown”));
Select dropdown= new Select(mySelectElement);
//To select an option – selectByVisibleText, selectByIndex, selectByValue
//selectByIndex
dropdown.selectByIndex(2); // value is QTP
}
}

SelectByValue Method:

It works based on the ‘value‘ provided by us.

Syntax

1

dropdown.selectByValue(Value);

Sample program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

package softwareTestingMaterial;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class SelectMethod {

@Test
public static void captureScreenMethod() throws Exception{
System.setProperty(“webdriver.chrome.driver”,”D://Selenium Environment//Drivers//chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“https://www.softwaretestingmaterial.com/sample-webpage-to-automate/”);
driver.navigate().refresh();
//Once you got the select object initialised then you can access all the methods of select class.
//Identify the select HTML element:
Thread.sleep(10000);
WebElement mySelectElement = driver.findElement(By.name(“dropdown”));
Select dropdown= new Select(mySelectElement);
//To select an option – selectByVisibleText, selectByIndex, selectByValue
//selectByValue
dropdown.selectByValue(“ddmanual”); // value is Manual Testing
}
}

DeSelect Methods With Examples:

DeselectByVisibleText Method:

It works based on the ‘visible text‘ which we provide

Syntax:

1

dropdown.deselectByVisibleText();

Sample program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

package softwareTestingMaterial;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class SelectMethod {

@Test
public static void captureScreenMethod() throws Exception{
System.setProperty(“webdriver.chrome.driver”,”D://Selenium Environment//Drivers//chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“https://www.softwaretestingmaterial.com/sample-webpage-to-automate/”);
driver.navigate().refresh();
//Once you got the select object initialised then you can access all the methods of select class.
//Identify the select HTML element:
Thread.sleep(10000);
WebElement mySelectElement = driver.findElement(By.name(“multipleselect[]”));
Select dropdown= new Select(mySelectElement);
//To deselect an option
//the deselect method will throw UnsupportedOperationException if the SELECT does not support multiple selections
dropdown.selectByVisibleText(“Performance Testing”);
Thread.sleep(2000);
dropdown.deselectByVisibleText(“Performance Testing”);
}
}

DeselectByIndex Method:

It works based on the ‘index value’ which we provide

Syntax:

1

dropdown.deselectByIndex();

Sample program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

package softwareTestingMaterial;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class SelectMethod {

@Test
public static void captureScreenMethod() throws Exception{
System.setProperty(“webdriver.chrome.driver”,”D://Selenium Environment//Drivers//chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“https://www.softwaretestingmaterial.com/sample-webpage-to-automate/”);
driver.navigate().refresh();
//Once you got the select object initialised then you can access all the methods of select class.
//Identify the select HTML element:
Thread.sleep(10000);
WebElement mySelectElement = driver.findElement(By.name(“multipleselect[]”));
Select dropdown= new Select(mySelectElement);
//To deselect an option
//the deselect method will throw UnsupportedOperationException if the SELECT does not support multiple selections
dropdown.selectByIndex(2);
Thread.sleep(2000);
dropdown.deselectByIndex(2);
}
}

DeselectByValue Method:

It works based on the ‘value‘ provided by us.

Syntax:

1

dropdown.deselectByValue();

Sample program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

package softwareTestingMaterial;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class SelectMethod {

@Test
public static void captureScreenMethod() throws Exception{
System.setProperty(“webdriver.chrome.driver”,”D://Selenium Environment//Drivers//chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“https://www.softwaretestingmaterial.com/sample-webpage-to-automate/”);
driver.navigate().refresh();
//Once you got the select object initialised then you can access all the methods of select class.
//Identify the select HTML element:
Thread.sleep(10000);
WebElement mySelectElement = driver.findElement(By.name(“multipleselect[]”));
Select dropdown= new Select(mySelectElement);
//To deselect an option
//the deselect method will throw UnsupportedOperationException if the SELECT does not support multiple selections
dropdown.selectByValue(“msagile”);
Thread.sleep(2000);
dropdown.deselectByValue(“msagile”);
}
}

DeselectAll Method:

It is to deselect all the selected options at once

Syntax:

1

dropdown.deselectAll( );

Sample program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

package softwareTestingMaterial;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class SelectMethod {

@Test
public static void captureScreenMethod() throws Exception{
System.setProperty(“webdriver.chrome.driver”,”D://Selenium Environment//Drivers//chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“https://www.softwaretestingmaterial.com/sample-webpage-to-automate/”);
driver.navigate().refresh();
//Once you got the select object initialised then you can access all the methods of select class.
//Identify the select HTML element:
Thread.sleep(10000);
WebElement mySelectElement = driver.findElement(By.name(“multipleselect[]”));
Select dropdown= new Select(mySelectElement);
//To deselect an option
//the deselect method will throw UnsupportedOperationException if the SELECT does not support multiple selections
dropdown.selectByValue(“msagile”);
Thread.sleep(2000);
dropdown.deselectAll();
}
}

In order to get the selected option:

Sample program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

package softwareTestingMaterial;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class SelectMethod {

@Test
public static void captureScreenMethod() throws Exception{
System.setProperty(“webdriver.chrome.driver”,”D://Selenium Environment//Drivers//chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“https://www.softwaretestingmaterial.com/sample-webpage-to-automate/”);
driver.navigate().refresh();
//Once you got the select object initialised then you can access all the methods of select class.
//Identify the select HTML element:
Thread.sleep(10000);
WebElement mySelectElement = driver.findElement(By.name(“multipleselect[]”));
Select dropdown= new Select(mySelectElement);
WebElement option = dropdown.getFirstSelectedOption();
System.out.println(option.getText()); //output “Selenium”
}
}

In order to get the list of options from a dropdown:

Sample program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

package softwareTestingMaterial;

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class SelectMethod {

@Test
public static void captureScreenMethod() throws Exception{
System.setProperty(“webdriver.chrome.driver”,”D://Selenium Environment//Drivers//chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“https://www.softwaretestingmaterial.com/sample-webpage-to-automate/”);
driver.navigate().refresh();
//Once you got the select object initialised then you can access all the methods of select class.
//Identify the select HTML element:
Thread.sleep(10000);
WebElement mySelectElement = driver.findElement(By.name(“multipleselect[]”));
Select dropdown= new Select(mySelectElement);
List<WebElement> options = dropdown.getOptions();
for (WebElement option : options) {
System.out.println(option.getText()); //output “Selenium”, “QTP”, “Manual Testing”, “Automation Testing”, “Performance Testing”*/
}
}
}

If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.

How To Upload File Using AutoIT And SendKeys In Selenium WebDriver

In this post we are going to see on how to upload file using AutoIT and sendKeys method in Selenium WebDriver. There are two cases which are majorly used to upload file in Selenium WebDriver such as using SendKeys Method and using AutoIT Script.

Also Read: How To Download File Using AutoIT in Selenium WebDriver

1. Upload file using SendKeys method in Selenium WebDriver:

Its very straightforward. Using sendkeys method, we could easily achieve this. Locate the text box and set the file path using sendkeys and click on submit button.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

package softwareTestingMaterial;
import java.io.IOException;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Upload {
public static void main(String[] args) throws IOException {
//Instantiation of driver object. To launch Firefox browser
WebDriver driver = new FirefoxDriver();
//To open URL “http://softwaretestingmaterial.com”
driver.get(“http://softwaretestingplace.blogspot.com/2015/10/sample-web-page-to-test.html”);
//Locating ‘browse’ button
WebElement browse =driver.findElement(By.id(“uploadfile”));
//pass the path of the file to be uploaded using Sendkeys method
browse.sendKeys(“D:\\SoftwareTestingMaterial\\UploadFile.txt”);
//’close’ method is used to close the browser window
driver.close();
}
}
2. Upload file AutoIt Script in Selenium WebDriver:

If there is no text box to set the file path and only able to click on Browse button to upload the file in the windows popup box then we do upload file using AutoIt tool.

AutoIt Introduction:

AutoIt Tool is an open source tool. It is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying “runtimes” required!

Now the question is how we do upload file using AutoIT Tool in Selenium WebDriver.

Follow the below steps:

Download Autoit tool from here and install it
Open Programs – Autoit tool – SciTE Script Editor and add the below mentioned AutoIt script in Autoit editor and save it as ‘UploadFile.au3’ in your system
Convert it as ‘UploadFile.exe’
In Eclipse, add the below mentioned Selenium Script and run

Step 1: Download AutoIt tool and install

Step 2: Open SciTE Script editor and add the below mentioned AutoIt script and save it as ‘UploadFile.au3’ in your system.

AutoIt Script:

1
2
3

WinWaitActive(“File Upload”)
Send(“D:\SoftwareTestingMaterial\UploadFile.txt”)
Send(“{ENTER}”)

AutoIt Script Explanation:

Line 1 : WinWaitActive(“File Upload”)

Above line of code changes the focus of cursor on the Window popup box to upload file.

‘File Upload‘ is the name of the window popup when using Mozilla Firefox. If you want to use other browsers such as Chrome you need to pass the value as ‘Open‘ (‘Open’ is the name of the window popup) and for IE you need to pass the value as ‘File To Upload’ (‘File To Upload’ is the name of the window popup)

Line 2 : Send(“Path of the document”)

Once the window popup is active, it sets the path of the document which needs to be uploaded

Send(“D:\SoftwareTestingMaterial\UploadFile.txt”)

Line 3 : Send(“{ENTER}”)

After that it clicks on Open button which will upload the document

Step 3: Once the file is saved, we need to convert the ‘UploadFile.au3’ to ‘UploadFile.exe’. To do this we need to compile the ‘UploadFile.au3’

Right click on the file ‘UploadFile.au3’ and click on ‘Compile Script’ to generate an executable file ‘UploadFile.exe’

Step 4: In Eclipse, add the below mentioned Selenium Script and run

Given clear explanation in the comments section with in the program itself. Please go through it to understand the flow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

package softwareTestingMaterial;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Upload {
public static void main(String[] args) throws IOException {
//Instantiation of driver object. To launch Firefox browser
WebDriver driver = new FirefoxDriver();
//To open URL “http://softwaretestingmaterial.com”
driver.get(“http://softwaretestingplace.blogspot.com/2015/10/sample-web-page-to-test.html”);
//Locating ‘browse’ button
WebElement browse =driver.findElement(By.id(“uploadfile”));
//To click on the ‘browse’ button
browse.click();
//To call the AutoIt script
Runtime.getRuntime().exec(“D:\\SoftwareTestingMaterial\\AutoIt\\Uploadfile.exe”);
//’close’ method is used to close the browser window
driver.close();
}
}

In the above Selenium Script, we did call the AutoIt Script after clicking on the browser button which transfers windows popup box and upload the required file.

Syntax:

1

Runtime.getRuntime().exec(“File Path of AutoIt.exe”);

Runtime.getRuntime().exec(“D:\\SoftwareTestingMaterial\\AutoIt\\Uploadfile.exe”);

This way we could upload a file using AutoIT

If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.

How To Handle Javascript Alerts/PopUps In Selenium WebDriver

In this post, we see how to handle javascript alerts/popus. Alerts are basically popup boxes that take your focus away from the current browser and forces you to read the alert message. You need to do some action such as accept or dismiss the alert box to resume your task on the browser.

To handle alerts popupswe need to do switch to the alert window and call Selenium WebDriver Alert API methods.

There are two types of alerts.

Windows Based
Web Based/Browser Based

Here in this post, I confine to Java Script Alerts (A.K.A. Browser/Web Based Alerts).

For Windows Based, Please check the below link.

How To Handle Windows Based Pop-ups Using AutoIT (WILL UPDATE SOON)

To handle Browser based Alerts (Web based alert popups), we use Alert Interface. The Alert Interface provides some methods to handle the popups.

While running the WebDriver script, the driver control will be on the browser even after the alert generated which means the driver control will be behind the alert pop up. In order to switch the control to alert pop up, we use the following command :

1

driver.switchTo().alert();

Once we switch the control from browser to the alert window. We can use the Alert Interface methods to do required actions such as accepting the alert, dismissing the alert, get the text from the alert window, writing some text on the alert window etc.,

Let’s see the Alert Interface Methods.

We need to Import a package org.openqa.selenium.Alert to handle the alerts in Selenium.

To get a handle to the open alert:

1

Alert alert = driver.switchTo().alert();

To Click on OK button:

1

alert.accept();

To click on Cancel button.

1

alert.dismiss()

To get the text which is present on the Alert.

1

alert.getText();

To enter the text into the alert box

1

alert.sendkeys(String stringToSend);

To Authenticate by passing the credentials

1

alert.authenticateUsing(Credentials credentials)

Sample Program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

package softwareTestingMaterial;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class AlertInterface {

@Test
public void alertWindow() throws Exception{
System.setProperty(“webdriver.chrome.driver”, “D:\\Selenium Environment\\Drivers\\chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.get(“http://softwaretestingplace.blogspot.com/2017/03/javascript-alert-test-page.html”);
driver.findElement(By.xpath(“//*[@id=’content’]/button”)).click();
Thread.sleep(3000);
Alert alert = driver.switchTo().alert();
String print = alert.getText();
System.out.println(print);
alert.accept();
Thread.sleep(3000);
driver.findElement(By.xpath(“//*[@id=’content’]/button”)).click();
Thread.sleep(3000);
alert.dismiss();
driver.close();
}
}

If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.

How To Handle Multiple Windows Using Selenium WebDriver

In this post, we will see how to handle multiple windows using Selenium WebDriver. In real time, we face many scenarios, where an application throws multiple popups. We can easily achieve this using Windows Handles in Selenium WebDriver. We use ‘Switch To’ method which allows us to switch control from one window to other.

Here is a program which handles multiple windows. Given clear explanation in the comments section within the program itself. Please go through it to understand the flow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

package softwareTestingMaterial;
import org.testng.annotations.Test;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class MultipleWindowsClass{
@Test
public void testMultipleWindows() throws InterruptedException{
System.setProperty(“webdriver.gecko.driver”, System.getProperty(“user.dir”)+”\\src\\test\\java\\drivers\\geckodriver.exe”);
// To open browser
WebDriver driver=new FirefoxDriver();
// To maximize browser
driver.manage().window().maximize();
// To open Naukri website with multiple windows
driver.get(“http://www.naukri.com/”);
// It will return the parent window name as a String
String mainWindow=driver.getWindowHandle();
// It returns no. of windows opened by WebDriver and will return Set of Strings
Set<String> set =driver.getWindowHandles();
// Using Iterator to iterate with in windows
Iterator<String> itr= set.iterator();
while(itr.hasNext()){
String childWindow=itr.next();
// Compare whether the main windows is not equal to child window. If not equal, we will close.
if(!mainWindow.equals(childWindow)){
driver.switchTo().window(childWindow);
System.out.println(driver.switchTo().window(childWindow).getTitle());
driver.close();
}
}
// This is to switch to the main window
driver.switchTo().window(mainWindow);
}
}

Mouse Hover Actions Using Actions Class In Selenium
Mouse Hover Actions Using Actions Class:

Sometimes, sub menu items render in DOM only when we mouse hover on main menu. In that case, we face difficulty to click on sub menu item. In order to perform mouse hover actions, we need to chain all of the actions that we want to achieve in one go. To do this we need to make the driver move to the parent element that has child elements and click on the child element.

To achieve this we use Actions class in Selenium WebDriver.

Must Read: Actions Class in Selenium WebDriver

Create object of an Actions Class by passing the WebDriver instance. With the object of the Actions class, driver moves to the main menu and then to the sub menu and click on it.

Let’s see some scenarios.

Mouse hover actions on an element using Actions Class:

1
2
3
4
5

WebElement ele = driver.findElement(By.xpath(“xpath”));
//Create object ‘action’ of an Actions class
Actions action = new Actions(driver);
//Mouseover on an element
action.moveToElement(ele).perform();

Mouse hover actions on a sub-element using Actions Class:

If we want to click on the sub-element, first we need to mouse hover on the parent-element and then sub-element and click on it.

1
2
3
4
5
6
7
8
9
10
11
12
13

//Main Menu
WebElement mainMenu = driver.findElement(By.linkText(“main_menu_link”));
//Create object ‘action’ of an Actions class
Actions actions = new Actions(driver);
//To mouseover on main menu
actions.moveToElement(mainMenu);

//Sub Menu
WebElement subMenu = driver.findElement(By.linkText(“sub_menu_link”));
//To mouseover on sub menu
actions.moveToElement(subMenu);
//build() method is used to compile all the actions into a single step
actions.click().build().perform();

Or

1
2
3
4
5
6

//Main Menu
WebElement mainMenu = driver.findElement(By.linkText(“main_menu_link”));
//Create object ‘action’ of an Actions class
Actions action = new Actions(driver);
//moving to the main menu and then sub menu and clicking on it using object of the Actions class
action.moveToElement(mainMenu).moveToElement(driver.findElement(By.linkText(“sub_menu_link

How To Perform Right Click Action (Context Click) In Selenium
Perform Right Click Action In Selenium:

In some scenarios, we may need to do right click action / context click on an element to do some actions. We use Actions class in Selenium WebDriver to work on Mouse and Keyboard Actions. Check out the below link for detailed explanation of Actions Class.

Must Read: Actions Class in Selenium WebDriver

Coming back to the current post, here we I take a scenario to do right click action on an element and get the text of an item

Scenario to be automated:

Launch the web browser and open the application
Find the required element and do right click on the element
Go to the options ‘copy’ and get the text of it and print it
Close the browser to end the program

Copy the below mentioned script and work on this scenario.

Given clear explanation in the comments section with in the program itself. Please go through it to understand the flow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

package softwareTestingMaterial;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class ActionsClass {

@Test
public void textInCaps() throws InterruptedException{
//Instantiating the WebDriver interface.
System.setProperty(“webdriver.chrome.driver”, “D:\\Selenium Environment\\Drivers\\chromedriver.exe”);
WebDriver driver = new ChromeDriver();
//Open the required URL
driver.get(“http://swisnl.github.io/jQuery-contextMenu/demo.html”);
//To maximize the browser
driver.manage().window().maximize();
//Create an object ‘action’ of an Actions class
Actions action = new Actions(driver);
By locator = By.cssSelector(“.context-menu-one”);
//Wait for the element. Used Explicit wait
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
WebElement rightClickElement=driver.findElement(locator);
//contextClick() method to do right click on the element
action.contextClick(rightClickElement).build().perform();
WebElement getCopyText =driver.findElement(By.cssSelector(“.context-menu-icon-copy”));
//getText() method to get the text value
String GetText = getCopyText.getText();
//To print the value
System.out.println(GetText);
//To close the browser
driver.close();
}
}

If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.

How To Perform Double Click Action In Selenium WebDriver
Perform Double Click Action In Selenium:

In some scenarios, we may need to do double click action on a particular element to move further. In such cases, we use Actions class in Selenium WebDriver to work on Mouse and Keyboard Actions. Check out the below link for detailed explanation of Actions Class.

Must Read: Actions Class in Selenium WebDriver

Scenario to be automated:

Launch the web browser and open the application
Find the required element and do double click on the element
Close the browser to end the program

Copy the below mentioned script and work on this scenario.

Given clear explanation in the comments section with in the program itself. Please go through it to understand the flow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

package softwareTestingMaterial;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;

public class ActionsClass {

@Test
public void doubleClick() throws InterruptedException{
System.setProperty(“webdriver.chrome.driver”, “D:\\Selenium Environment\\Drivers\\chromedriver.exe”);
WebDriver driver = new ChromeDriver();
//Open the required URL where you could do double click action
driver.get(“http://api.jquery.com/dblclick/”);
//Maximize the browser
driver.manage().window().maximize();
//As per the above URL we need to switch to frame. The targeted element is in the frame
driver.switchTo().frame(0);
//Create the object ‘action’
Actions action = new Actions(driver);
//Find the targeted element
WebElement ele = driver.findElement(By.cssSelector(“html>body>div”));
//Here I used JavascriptExecutor interface to scroll down to the targeted element
((JavascriptExecutor) driver).executeScript(“arguments[0].scrollIntoView();”, ele);
//used doubleClick(element) method to do double click action
action.doubleClick(ele).build().perform();
//Once clicked on the element, the color of element is changed to yellow color from blue color
//driver.close();
}
}

If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.

Drag And Drop Using Actions Class In Selenium WebDriver
Drag And Drop Using Actions Class:

In some applications, we may face a situation to automate drag and drop an item from one location to another location. We could not achieve these using basic elements. Selenium has provided an “Actions” class to handle this kind of scenarios. We overcome this kind of scenarios such as drag and drop using Actions Class.

To achieve this we use Actions class in Selenium WebDriver. You could find a detailed explanation on Actions in Selenium using below link.

1
2
3
4
5
6
7
8

//To get source locator
WebElement sourceLocator = driver.findElement(By.xpath(“xpath”));
//To get target locator
WebElement targetLocator = driver.findElement(By.xpath(“xpath”));
//create object ‘action’ of Actions class
Actions action = new Actions(driver);
//use dragAndDrop() method. It accepts two parametes source and target.
action.dragAndDrop(sourceLocator, targetLocator).build().perform();

Sample Script:

Given clear explanation in the comments section within the program itself. Please go through it to understand the flow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

package softwareTestingMaterial;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class ActionsClass {

@Test
public void actionsClass() throws InterruptedException{
System.setProperty(“webdriver.chrome.driver”, “D:\\Selenium Environment\\Drivers\\chromedriver.exe”);
WebDriver driver = new ChromeDriver();
//Create an object ‘action’
Actions action = new Actions(driver);
//navigate to the required url where we could do drag and drop action
driver.get(“http://jqueryui.com/droppable/”);
//WebdriverWait is used to wait for a frame to be available. Once it is availble we switch to the frame to achieve our task
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector(“.demo-frame”)));
//To get source locator
WebElement sourceLocator = driver.findElement(By.cssSelector(“#draggable”));
//To get target locator
WebElement targetLocator = driver.findElement(By.cssSelector(“#droppable”));
//dragAndDrop(source, target) method accepts two parameters source and locator.
//used dragAndDrop method to drag and drop the source locator to target locator
action.dragAndDrop(sourceLocator, targetLocator).build().perform();
}
}

If you are not a regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.

How To Capture Screenshot Using Selenium WebDriver
Capture Screenshot Using Selenium WebDriver:

Test cases may fail while executing the test cases. While we are executing the test cases manually we just take a screenshot and place in a result repository. The same can be done by using Selenium WebDriver. Here in this post, we see how to capture a screenshot using Selenium WebDriver.

Some of the scenarios we may need to capture screenshot using Selenium WebDriver.

i. Application issues
ii. Assertion Failure
iii. Difficulty to find Webelements on the web page
iv. Timeout to find Webelements on the web page

Syntax to capture and save the screenshot.

1

File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

Syntax to store it in our local drive

1

FileUtils.copyFile(screenshotFile, new File(“filename_with_path”));

For example:

1

FileUtils.copyFile(screenshotFile, new FIle(“D:\\screenshot.png”));

Below mentioned script shows how to capture a screenshot using Selenium WebDriver.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

package softwareTestingMaterial;

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class CaptureScreenshot {

@Test
public static void captureScreenMethod() throws Exception{
System.setProperty(“webdriver.gecko.driver”,”D://Selenium Environment//Drivers//geckodriver.exe”);
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(“https://www.softwaretestingmaterial.com/capture-screenshot-using-selenium-webdriver”);
File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File(“D:\\SoftwareTestingMaterial.png”));
driver.close();
driver.quit();
}
}

If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.

TestNG Parameterization Using DataProviders | TestNG Tutorial
TestNG Parameterization Using DataProviders

Parameterized tests allow developers to run the same test over and over again using different values.

There are two ways to set these parameters:

with testng.xml
with Data Providers

Let’s see passing parameters using DataProviders:

Specifying parameters in testng.xml might not be sufficient if you need to pass complex parameters, or parameters that need to be created from Java (complex objects, objects read from a property file or a database, etc…). In this case, you can use a Data Provider to supply the values you need to test.  A Data Provider is a method on your class that returns an array of objects.  This method is annotated with @DataProvider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

package softwareTestingMaterial;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderClass {

// This method takes data as input parameters. The attribute dataprovider is mapped to “getData”
@Test (dataProvider=”getData”)
// Number of columns should match the number of input parameters
public void loginTest(String Uid, String Pwd){
System.out.println(“UserName is “+ Uid);
System.out.println(“Password is “+ Pwd);
}

//If the name is not supplied, the data provider’s name automatically defaults to the method’s name.
//A data provider returns an array of objects.
@DataProvider(name=”getData”)
public Object[][] getData(){
//Object [][] data = new Object [rowCount][colCount];
Object [][] data = new Object [2][2];

data [0][0] = “FirstUid”;
data [0][1] = “FirstPWD”;

data[1][0] = “SecondUid”;
data[1][1] = “SecondPWD”;

return data;

}
}

Console Output:

1
2
3
4
5
6
7
8
9
10
11

[TestNG] Running:

UserName is FirstUid
Password is FirstPWD
UserName is SecondUid
Password is SecondPWD

===============================================
softwaretestingmaterial
Total tests run: 2, Failures: 0, Skips: 0
===============================================

Selenium Wait Commands – Implicit, Explicit, Fluent Waits | Selenium WebDriver Tutorial

Selenium Wait commands play an important role while executing Selenium tests. Let’s see different wait commands such as “Implicit“, and “Explicit” wait commands in selenium.

While executing scripts, sometimes we may face an exception “Element Not Visible Exception“. This exception appears when there is a delay in loading time of the elements which we are interacting. To overcome this issue we need to use Wait Commands. Using the Selenium Wait Commands, our script will wait for the elements to load for certain time before continuing with the next step.

Different Types of Selenium Wait Commands are:
Implicit Wait
Explicit Wait – WebDriverWait
FluentWait
Implicit Wait:

The implicit wait tells to the WebDriver to wait for certain amount of time before it throws an exception. Once we set the time, WebDriver will wait for the element based on the time we set before it throws an exception. The default setting is 0 (zero). We need to set some wait time to make WebDriver to wait for the required time.

Note: Implicit Wait is in place for the entire time the browser is open. Time taken to search all the elements are based on the time fixed for the implicit wait.

Syntax:

1

driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

Implicit Wait time is applied to all the elements in the script.

Implicit wait will accept 2 parameters, the first parameter will accept the time as an integer value and the second parameter will accept the time measurement in terms of SECONDS, MINUTES, MILISECOND, MICROSECONDS, NANOSECONDS, DAYS, HOURS, etc.

Explicit Wait:

Explicit waits are confined to a particular web element. Explicit Wait is code you define to wait for a certain condition to occur before proceeding further in the code.

Explicit wait is of two types:

WebDriverWait
FluentWait

WebDriverWait:

WebDriverWait is applied on certain element with defined expected condition and time. This wait is only applied to the specified element. This wait can also throw exception when element is not found.

The following are the Expected Conditions that can be used in Explicit Wait

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

Syntax:

1
2
3

//WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
WebDriverWait wait = new WebDriverWait (driver, 20);
wait.until(ExpectedConditions.VisibilityofElementLocated(By.xpath(“”//button[@value=’Save Changes’]””)));

FluentWait:

FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.

To say in effortless manner, it tries to find the web element repeatedly at regular intervals of time until the timeout or till the object gets found.

We use Fluent Wait commands mainly when we have web elements which sometimes visible in few seconds and some times take more time than usual to visible. Mainly in Ajax applications.

Syntax:

1
2
3
4
5
6
7
8
9
10

Wait wait = new FluentWait(WebDriver reference)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);

WebElement foo=wait.until(new Function<WebDriver, WebElement>() {
public WebElement applyy(WebDriver driver) {
return driver.findElement(By.id(“foo”));
}
});

Example:

1
2
3
4

Wait wait = new FluentWait<WebDriver>(driver)
.withTimeout(45, TimeUnit.SECONDS)
.pollingevery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);

Fluent Wait uses two parameters – timeout value and polling frequency. In the above syntax we took time out value as 45 seconds and polling frequency as 5 seconds.
The maximum amount of time (45 seconds) to wait for a condition and the frequency (5 seconds) to check the success or failure of a specified condition. If the element is located with in this time frame it will perform the operations else it will throw an “ElementNotVisibleException”.

Selenium Wait Commands – Implicit, Explicit, Fluent Waits | Selenium WebDriver Tutorial

Selenium Wait commands play an important role while executing Selenium tests. Let’s see different wait commands such as “Implicit“, and “Explicit” wait commands in selenium.

While executing scripts, sometimes we may face an exception “Element Not Visible Exception“. This exception appears when there is a delay in loading time of the elements which we are interacting. To overcome this issue we need to use Wait Commands. Using the Selenium Wait Commands, our script will wait for the elements to load for certain time before continuing with the next step.

Different Types of Selenium Wait Commands are:
Implicit Wait
Explicit Wait – WebDriverWait
FluentWait
Implicit Wait:

The implicit wait tells to the WebDriver to wait for certain amount of time before it throws an exception. Once we set the time, WebDriver will wait for the element based on the time we set before it throws an exception. The default setting is 0 (zero). We need to set some wait time to make WebDriver to wait for the required time.

Note: Implicit Wait is in place for the entire time the browser is open. Time taken to search all the elements are based on the time fixed for the implicit wait.

Syntax:

1

driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

Implicit Wait time is applied to all the elements in the script.

Implicit wait will accept 2 parameters, the first parameter will accept the time as an integer value and the second parameter will accept the time measurement in terms of SECONDS, MINUTES, MILISECOND, MICROSECONDS, NANOSECONDS, DAYS, HOURS, etc.

Explicit Wait:

Explicit waits are confined to a particular web element. Explicit Wait is code you define to wait for a certain condition to occur before proceeding further in the code.

Explicit wait is of two types:

WebDriverWait
FluentWait

WebDriverWait:

WebDriverWait is applied on certain element with defined expected condition and time. This wait is only applied to the specified element. This wait can also throw exception when element is not found.

The following are the Expected Conditions that can be used in Explicit Wait

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

Syntax:

1
2
3

//WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
WebDriverWait wait = new WebDriverWait (driver, 20);
wait.until(ExpectedConditions.VisibilityofElementLocated(By.xpath(“”//button[@value=’Save Changes’]””)));

FluentWait:

FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.

To say in effortless manner, it tries to find the web element repeatedly at regular intervals of time until the timeout or till the object gets found.

We use Fluent Wait commands mainly when we have web elements which sometimes visible in few seconds and some times take more time than usual to visible. Mainly in Ajax applications.

Syntax:

1
2
3
4
5
6
7
8
9
10

Wait wait = new FluentWait(WebDriver reference)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);

WebElement foo=wait.until(new Function<WebDriver, WebElement>() {
public WebElement applyy(WebDriver driver) {
return driver.findElement(By.id(“foo”));
}
});

Example:

1
2
3
4

Wait wait = new FluentWait<WebDriver>(driver)
.withTimeout(45, TimeUnit.SECONDS)
.pollingevery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);

Fluent Wait uses two parameters – timeout value and polling frequency. In the above syntax we took time out value as 45 seconds and polling frequency as 5 seconds.
The maximum amount of time (45 seconds) to wait for a condition and the frequency (5 seconds) to check the success or failure of a specified condition. If the element is located with in this time frame it will perform the operations else it will throw an “ElementNotVisibleException”.

Implicit Waits in Selenium | Selenium WebDriver Tutorial

Implicit waits tell to the WebDriver to wait for certain amount of time before it throws an exception. Once we set the time, WebDriver will wait for the element based on the time we set before it throws an exception. The default setting is 0 (zero). We need to set some wait time to make WebDriver to wait for the required time.

Note: Implicit Wait is in place for the entire time the browser is open. Time taken to search all the elements are based on the time fixed for the implicit wait.

Syntax:

1

driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

Implicit Wait time is applied to all the elements in the script.

Implicit wait will accept 2 parameters, the first parameter will accept the time as an integer value and the second parameter will accept the time measurement in terms of SECONDS, MINUTES, MILISECOND, MICROSECONDS, NANOSECONDS, DAYS, HOURS, etc.

Test script with an explanation – Implicit Waits in Selenium:

Find the sample script (using Java) mentioned below. Execute it to see the functionality of Implicit Wait in Selenium.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

package waits;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ImplicitWaits {
public static void main(String[] args) {
//To create a new instance of Firefox Driver
WebDriver driver = new FirefoxDriver();
//Implicit Wait – Here the specified Implicit Wait time frame is 15 seconds.
//It waits 15 seconds of time frame for the element to load.
//It throws an exception, if the element is not loaded within the specified time frame
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//To open a website “Software Testing Material”
driver.get(“http://www.softwaretestingmaterial.com”);
//To maximize the browser window
driver.manage().window().maximize();
//To close the browser
driver.close();
}
}

There are some instances when a particular element takes more time (eg. 1 min) to load. In such cases setting a huge time to Implicit wait makes the browser to wait for the same time for every element. To avoid this, we need to implement Explicit Waits.

If you are not regular reader of my blog then I highly recommend you to sign up for the free email newsletter using the below link.

WebDriverWait In Selenium | Selenium WebDriver Tutorial

Selenium WebDriverWait is one of the Explicit waits.

Explicit waits are confined to a particular web element. Explicit Wait is code you define to wait for a certain condition to occur before proceeding further in the code.

Explicit wait is of two types:

WebDriverWait
FluentWait
WebDriverWait In Selenium:

It is applied on certain element with defined expected condition and time. This wait is only applied to the specified element. This wait can also throw exception when element is not found.

We could avoid throwing exception in Selenium. Check this post.

The following are the Expected Conditions that can be used in Explicit Wait

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

Syntax:

1
2
3

//WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
WebDriverWait wait = new WebDriverWait (driver, 20);
wait.until(ExpectedConditions.VisibilityofElementLocated(By.xpath(“”//button[@value=’Save Changes’]””)));

Test script with an explanation:

Find the sample script (using Java) mentioned below. Execute it to see the functionality.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

package waits;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ExplicitWaits {
public static void main(String[] args) {
//To create a new instance of Firefox Driver
WebDriver driver = new FirefoxDriver();
//To open a website “Software Testing Material”
driver.get(“http://www.softwaretestingmaterial.com”);
//To maximize the browser window
driver.manage().window().maximize();
//This waits up to 15 seconds before throwing a TimeoutException or if it finds the element will return it in 0 – 15 seconds
WebDriverWait wait = new WebDriverWait (driver, 15);
//Title of the webpage is “Software Testing Material – A site for Software Testers”
wait.until(ExpectedConditions.titleIs(“Software Testing Material – A site for Software Testers”));
//If the above condition met then the browser will be closed
//To close the browser
driver.close();
//Change the title “Software Testing Material – A site for Software Testers” as “xyz” in the script and try
//You will face an execption – Exception in thread “main” org.openqa.selenium.TimeoutException: Timed out after 20 seconds waiting for title to be “Software Testing Material – A site for Software Tes”. Current title: “xyz”
}
}

The default pooling period for implicit and explicit wait is 250 ms. Here in Fluent wait, we could change the default pooling period based on our requirement. Also we could ignore any exception while pooling element such as No Such Element exception.

If you are not regular reader of my blog then I highly recommend you to sign up for the free email newsletter using the below link.

Selenium FluentWait | Selenium WebDriver Tutorial

Selenium FluentWait is one of the Explicit waits.

Explicit waits are confined to a particular web element. Explicit Wait is code you define to wait for a certain condition to occur before proceeding further in the code.

Types of Explicit Waits:

WebDriverWait
FluentWait

Here we discuss about Selenium FluentWait. Click on this link for WebDriverWait.

Selenium FluentWait:

FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.

To say in effortless manner, it tries to find the web element repeatedly at regular intervals of time until the timeout or till the object gets found.

We use FluentWait commands mainly when we have web elements which sometimes visible in few seconds and some times take more time than usual. Mainly in Ajax applications. We could set the default pooling period based on our requirement. We could ignore any exception while polling an element.

Syntax:

1
2
3
4
5
6
7
8
9
10

Wait wait = new FluentWait(WebDriver reference)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);

WebElement foo=wait.until(new Function<WebDriver, WebElement>() {
public WebElement applyy(WebDriver driver) {
return driver.findElement(By.id(“foo”));
}
});

Example:

1
2
3
4

Wait wait = new FluentWait<WebDriver>(driver)
.withTimeout(45, TimeUnit.SECONDS)
.pollingevery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);

FluentWait uses two parameters mainly – timeout value and polling frequency. In the above syntax we took time out value as 45 seconds and polling frequency as 5 seconds. The maximum amount of time (45 seconds) to wait for a condition and the frequency (5 seconds) to check the success or failure of a specified condition. If the element is located with in this time frame it will perform the operations else it will throw an “ElementNotVisibleException”

Test script with an explanation – Selenium FluentWait:

Find the sample script (using Java) mentioned below. Execute it to see the functionality of a Selenium FluentWait.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

package waits;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.FluentWait; //FluentWait is a Class and it is a part of this package
import org.testng.annotations.Test;

import com.google.common.base.Function;

public class FluentWaitClass {
@Test
public static void fluentWaitMethod(){
System.setProperty(“webdriver.gecko.driver”,”D://Selenium Environment//Drivers//geckodriver.exe”);
WebDriver driver = new FirefoxDriver();
driver.get(“http://softwaretestingplace.blogspot.com/2017/02/selenium-fluent-wait.html”);
driver.findElement(By.xpath(“//*[@id=’post-body-5280210221385817166′]/div[1]/button”)).click();

FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);

WebElement element = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
WebElement element = driver.findElement(By.xpath(“//*[@id=’softwareTestingMaterial’]”));
String getTextOnPage = element.getText();
if(getTextOnPage.equals(“Software Testing Material – DEMO PAGE”)){
System.out.println(getTextOnPage);
return element;
}else{
System.out.println(“FluentWait Failed”);
return null;
}
}
});
}
}

If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.

Handling Excel Files Using Apache POI In Selenium WebDriver

Handling excel files Using Apache POI in Selenium WebDriver. As we all know Selenium supports only Web browser automation. We need to get the help of third party API like Apache POI to handle (read and write) excel files using Selenium WebDriver.

What is Apache POI?

Apache POI is an open source library developed and distributed by Apache Software Foundation to design or modify Microsoft Office files using Java program. It is a popular API that allows to work around excel files using Java Programs. In short, you can read and write MS Excel files using Java. Apache POI is your Java Excel solution.
You’d use HSSF if you needed to read or write an Excel file using Java (XLS). You’d use XSSF if you need to read or write an OOXML Excel file using Java (XLSX). It has many predefined methods, classes, and interfaces.

Official website of Apache POI

Workbook: HSSFWorkbook and XSSFWorkbook classes implement this interface
HSSFWorkbook: It is a class represents XLS file
XSSFWorkbook: It is a class represents XLSX file
Sheet: HSSFWorkbook and XSSFWorkbook classes implement this interface
HSSFSheet: It is a class represents a sheet in a XLS file
XSSFSheet: It is a class represents a sheet in a XLSX file
Row: HSSFWorkbook and XSSFWorkbook classes implement this interface
HSSFRow: It is a class represents a row in a sheet of XLS file
XSSFRow: It is a class represents a row in a sheet of XLSX file
Cell: HSSFWorkbook and XSSFWorkbook classes implement this interface
HSSFCell: It is a class represents a cell in a row of XLS file
XSSFCell: It is a class represents a cell in a row of XLSX file

Download the jar files using the above mentioned link. All jar files will come in a zip file. Extract it and Add all jar files in the Project.

Note: How to add Jar files – Select Project and Right click on the Project – Go to ‘Build path’ – Go to ‘Configure build path’ – Click on ‘lib’ section – Add external jar

We do handle excel files using Apache POI in Selenium WebDriver very often. Mainly coming to Automation framework (Data Driven Framework), we call the data from excel file and write the data in the excel file. Below links give an idea about Read/Write excel files using Selenium WebDriver.

How to Read Excel Files Using Apache POI In Selenium WebDriver

Assuming that you have already downloaded and configured Apache POI jars in your project. If not, follow the below steps:

Step 1– Download Apache POI jar file

Download link of Apache POI Jars.

Step 2– Add download jar files

Steps to add jar files:

Select Project and Right click on the Project – Go to ‘Build path’ – Go to ‘Configure build path’ – Click on ‘lib’ section – Add external jar

Complete Guide: Handling Excel Files Using Apache POI

Precondition:

Create an xlsx file and save it at particular location. Enter some data to read using Selenium. Close the created excel file before executing the script. (I have placed an excel file ‘Test.xlsx’ in my D Driver and my sheet name is TestData.)
Go to option “Format Cells” and under Number Tab option, select Text and click on OK. By default it will be general, you need to make it as Number. If you don’t make it as text, there is a chance of NullPointerException error.

Below mentioned script shows how to read excel files in Selenium using Apache POI.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

package softwareTestingMaterial;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

//How to read excel files using Apache POI
public class ReadExcel {
public static void main (String [] args) throws IOException{
//I have placed an excel file ‘Test.xlsx’ in my D Driver
FileInputStream fis = new FileInputStream(“D:\\Test.xlsx”);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
//I have added test data in the cell A1 as “SoftwareTestingMaterial.com”
//Cell A1 = row 0 and column 0. It reads first row as 0 and Column A as 0.
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
System.out.println(cell);
System.out.println(sheet.getRow(0).getCell(0));
//String cellval = cell.getStringCellValue();
//System.out.println(cellval);

}
}

Console Output:

1

SoftwareTestingMaterial.com

If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.

How to Write Excel Files Using Apache POI In Selenium WebDriver

Assuming that you have already downloaded and configured Apache POI jars in your project. If not, follow the below steps:

Step 1– Download Apache POI jar file

Download link of Apache POI Jars.

Step 2– Add download jar files

Select Project and Right click on the Project – Go to ‘Build path’ – Go to ‘Configure build path’ – Click on ‘lib’ section – Add external jar

Precondition:

Create an xlsx file and save it at particular location. Enter some data to read using Selenium. Close the created excel file before executing the script. (I have placed an excel file ‘Test.xlsx’ in my D Driver  and my sheet name is TestData.)
Go to option “Format Cells” and under Number Tab option, select Text and click on OK. By default it will be general, you need to make it as Number. If you don’t make it as text, there is a chance of NullPointerException error.

Below mentioned script shows how to write excel files in Selenium using Apache POI.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

package softwareTestingMaterial;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteExcel {

public static void main (String [] args) throws IOException{
//create an object of Workbook and pass the FileInputStream object into it to create a pipeline between the sheet and eclipse.
FileInputStream fis = new FileInputStream(“D:\\Test.xlsx”);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
//call the getSheet() method of Workbook and pass the Sheet Name here.
//In this case I have given the sheet name as “TestData”
//or if you use the method getSheetAt(), you can pass sheet number starting from 0. Index starts with 0.
XSSFSheet sheet = workbook.getSheet(“TestData”);
//XSSFSheet sheet = workbook.getSheetAt(0);
//Now create a row number and a cell where we want to enter a value.
//Here im about to write my test data in the cell B2. It reads Column B as 1 and Row 2 as 1. Column and Row values start from 0.
//The below line of code will search for row number 2 and column number 2 (i.e., B) and will create a space.
//The createCell() method is present inside Row class.
Row row = sheet.createRow(1);
Cell cell = row.createCell(1);
//Now we need to find out the type of the value we want to enter.
//If it is a string, we need to set the cell type as string
//if it is numeric, we need to set the cell type as number
cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue(“SoftwareTestingMaterial.com”);
FileOutputStream fos = new FileOutputStream(“D:\\Test.xlsx”);
workbook.write(fos);
fos.close();
System.out.println(“END OF WRITING DATA IN EXCEL”);
}
}

Console Output:

1

END OF WRITING DATA IN EXCEL

If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.

Database Testing Using Selenium WebDriver – MSSQL Server
Database Testing Using Selenium WebDriver

In this post, let’s see how to do Database Testing using Selenium WebDriver. As we all know Selenium WebDriver is a tool to automate User Interface. We could only interact with Browser using Selenium WebDriver.

Sometimes, we may face a situation to get the data from the Database or to modify (update/delete) the data from the Database.  If we plan to automate anything outside the vicinity of a browser, then we need to use other tools to achieve our task. To achieve the Database connection and work on it, we need to use JDBC API Driver.

The Java Database Connectivity (JDBC) API provides universal data access from the Java programming language. Using the JDBC API, you can access virtually any data source, from relational databases to spreadsheets and flat files. It lets the user connect and interact with the Database and fetch the data based on the queries we use in the automation script. JDBC is a SQL level API that allows us to execute SQL statements. It creates a connectivity between Java Programming Language and the database.

Using JDBC Driver we could do the following

Establish a Database connection
Send SQL Queries to the Database
Process the results

Loading the required JDBC (Java DataBase Connectivity) Driver class:

1

Class.forName(“net.sourceforge.jtds.jdbc.Driver”);

Note: The parameter varies between Data bases such as MySQL, DB2 etc.,

Establishing a connection to the DataBase (MS SQL Server):

1

Connection con = DriverManager.getConnection(“DataBaseURL”, “userName”, “password”);

Connection URL Syntax (MS SQL Server):

1

jdbc:sqlserver://ipAddress:portNumber/dbName

Executing SQL Queries:

1
2
3

Statement sqlStatement = con.createStatement();
String sqlQuery = “SELECT * FROM table_name WHERE condition”;
ResultSet resSet = sqlStatement.executeQuery(sqlQuery);

Results from the executed query are stored in the ResultSet Object.

Fetching data from result set:

1
2
3

while (resSet.next()) {
System.out.println(resSet.getString(required_column_name));
}

Disconnecting the Database connection:

1

con.close();

List of Methods to process the results:

Note: Assuming that you have already Installed Database.

Steps to follow – Database Testing using Selenium WebDriver:
Click here to download the jar files.
Add the downloaded jar file to your project

Right click on your Java File – Click on Build Path – Configure build path – Select the libraries – Click on add external JARs – Select MSSQL Server JDBC jar – Click on open to add it to the project

3. Copy the below mentioned script and modify as per your requirement and execute it

Note: You could find the detailed explanation of the script in the code snippet below

Script to get the data from the Database – Database Testing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

package softwareTestingMaterial;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBTesting {
public static void selectQuery() throws SQLException, ClassNotFoundException {
String dbURL = “jdbc:sqlserver://ipAddress:portNumber/dbName”;
String username = myUserName;
String password = myPassword;
//Load MS SQL JDBC Driver
Class.forName(“net.sourceforge.jtds.jdbc.Driver”);
//Creating connection to the database
Connection con = DriverManager.getConnection(dbURL,username,password);
//Creating statement object
Statement st = con.createStatement();
String selectquery = “SELECT * FROM <tablename> WHERE <condition>”;
//Executing the SQL Query and store the results in ResultSet
ResultSet rs = st.executeQuery(selectquery);
//While loop to iterate through all data and print results
while (rs.next()) {
System.out.println(rs.getString(“transaction_datetime”));
}
//Closing DB Connection
con.close();
}
}

Script to update the data in the Database – Database Testing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

package softwareTestingMaterial;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBTesting {
public static void updateQuery() throws ClassNotFoundException, SQLException{
String dbURL = “jdbc:sqlserver://ipAddress:portNumber/dbName”;
String username = myUserName;
String password = myPassword;
String updatequery = “UPDATE <table_name> SET <column_name> = <some_value>”;

Class.forName(“net.sourceforge.jtds.jdbc.Driver”);
Connection con = DriverManager.getConnection(dbURL,username,password);
Statement stmt = con.createStatement();
stmt.executeUpdate(updatequery);
con.close();
}
}

Script to delete the data in the Database – Database Testing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

package softwareTestingMaterial;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBTesting {
public static void deleteQuery() throws SQLException, ClassNotFoundException {
String dbURL = “jdbc:sqlserver://ipAddress:portNumber/dbName”;
String username = myUserName;
String password = myPassword;
String query = “DELETE FROM <table_name>”;
Class.forName(“net.sourceforge.jtds.jdbc.Driver”);
Connection con = DriverManager.getConnection(dbURL,username,password);
Statement stmt = con.createStatement();
stmt.executeUpdate(query);
//Closing DB Connection
con.close();
}
}

I would like to conclude this post “MS SQL Database testing using Selenium WebDriver” here. If you find anything difficult, please comment below. Also, I have hand-picked few posts which will help you to learn more interview related stuff.

How To Handle AJAX Calls Using Selenium WebDriver
Handle Ajax Calls using Selenium:

Handling AJAX calls is one of the common issues when using Selenium WebDriver. We wouldn’t know when the AJAX call would get completed and the page has been updated. In this post, we see how to handle AJAX calls using Selenium.

AJAX stands for Asynchronous JavaScript and XML. AJAX allows the web page to retrieve small amounts of data from the server without reloading the entire page. AJAX sends HTTP requests from the client to server and then process the server’s response without reloading the entire page. To handle AJAX controls, wait commands may not work. It’s just because the actual page is not going to refresh.

When you click on a submit button, required information may appear on the web page without refreshing the browser. Sometimes it may load in a second and sometimes it may take longer. We have no control on loading time. The best approach to handle this kind of situations in selenium is to use dynamic waits (i.e. WebDriverWait in combination with ExpectedCondition)

Some of the methods which are available are as follows:

In the above post, we have discussed on titleIs() condition. Let’s see some other conditions in detail.

titleIs() – The expected condition waits for a page with a specific title.

1

wait.until(ExpectedConditions.titleIs(“Deal of the Day”));
elementToBeClickable() – The expected condition waits for an element to be clickable i.e. it should be present/displayed/visible on the screen as well as enabled.

1

wait.until(ExpectedConditions.elementToBeClickable(By.xpath(“xpath”)));
alertIsPresent() – The expected condition waits for an alert box to appear.

1

wait.until(ExpectedConditions.alertIsPresent()) !=null);
textToBePresentInElement() – The expected condition waits for an element having a certain string pattern.

1

wait.until(ExpectedConditions.textToBePresentInElement(By.id(“title’”), “text to be found”));

If you are not a regular reader of SoftwareTestingMaterial.com then I highly recommend you to signup for the free email newsletter using the below link.

WebDriver Event Listeners In Selenium | Selenium Tutorial

In this post, we see WebDriver Event Listeners in Selenium WebDriver. Listeners “listen” to the event defined in the selenium script and behave accordingly. The main purpose of using listeners is to create logs and reports. There are many types of listeners such as WebDriver Event Listeners and TestNG Listeners. Here in this post, we see WebDriver Event Listeners.

We need to know the following class and interface when we talk about listeners in Selenium.

WebDriverEventListener: This WebDriver Event Listener interface allows us to implement the methods

Once the script is executed, Selenium WebDriver does perform activities such as Type, Click, Navigate etc., To keep track of these activities we use WebDriver Event Listeners interface.

EventFiringWebDriver: This EventFiringWebDriver class actually fire WebDriver event

Lets see how to implement Listeners in Selenium WebDriver Script.

Step 1: Create a Class “EventCapture” to implement WebDriverEventListener methods

Step 2: Create another Class “ListenerMainClass” and write a script (which ever script you prefer)

Step 3: In the Class “ListenerMainClass“, Create EventFiringWebDriver object and pass driver object as a parameter

1

EventFiringWebDriver eventHandler = new EventFiringWebDriver(driver);

Step 4: In the Class “ListenerMainClass“, Create an object of the Class “EventCapture” where we implemented all the methods of WebDriverEventListener to register with EventFiringWebDriver

1

EventCapture eCapture = new EventCapture();

Lets see each step in detail to implement the WebDriver Event Listeners in Selenium:

Step 1: Create a Class “EventCapture” to implement WebDriverEventListener methods

1
2
3
4
5

package listeners;

public class EventCapture{

}

1
2
3
4
5
6
7

package listeners;

public class EventCapture implements WebDriverEventListener{

}

Mouse hover on WebDriverEventListener and import WebDriverEventListener Interface and mouse hover on EventCapture and click on “Add unimplemented methods” to add multiple unimplemented methods (without body)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

package listeners;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverEventListener;
//WebDriver Event Listeners
public class EventCapture implements WebDriverEventListener{

@Override
public void afterChangeValueOf(WebElement arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void afterClickOn(WebElement arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void afterFindBy(By arg0, WebElement arg1, WebDriver arg2) {
// TODO Auto-generated method stub

}

@Override
public void afterNavigateBack(WebDriver arg0) {
// TODO Auto-generated method stub

}

@Override
public void afterNavigateForward(WebDriver arg0) {
// TODO Auto-generated method stub

}

@Override
public void afterNavigateRefresh(WebDriver arg0) {
// TODO Auto-generated method stub

}

@Override
public void afterNavigateTo(String arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void afterScript(String arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void beforeChangeValueOf(WebElement arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void beforeClickOn(WebElement arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void beforeFindBy(By arg0, WebElement arg1, WebDriver arg2) {
// TODO Auto-generated method stub

}

@Override
public void beforeNavigateBack(WebDriver arg0) {
// TODO Auto-generated method stub

}

@Override
public void beforeNavigateForward(WebDriver arg0) {
// TODO Auto-generated method stub

}

@Override
public void beforeNavigateRefresh(WebDriver arg0) {
// TODO Auto-generated method stub

}

@Override
public void beforeNavigateTo(String arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void beforeScript(String arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void onException(Throwable arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

}

Here I am implementing afterNavigateBack, beforeNavigateBack methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

package listeners;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverEventListener;

public class EventCapture implements WebDriverEventListener{

@Override
public void afterChangeValueOf(WebElement arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void afterClickOn(WebElement arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void afterFindBy(By arg0, WebElement arg1, WebDriver arg2) {
// TODO Auto-generated method stub

}

@Override
public void afterNavigateBack(WebDriver arg0) {
// TODO Auto-generated method stub
System.out.println(“After Navigating Back “+arg0.getCurrentUrl());
}

@Override
public void afterNavigateForward(WebDriver arg0) {
// TODO Auto-generated method stub

}

@Override
public void afterNavigateRefresh(WebDriver arg0) {
// TODO Auto-generated method stub

}

@Override
public void afterNavigateTo(String arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void afterScript(String arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void beforeChangeValueOf(WebElement arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void beforeClickOn(WebElement arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void beforeFindBy(By arg0, WebElement arg1, WebDriver arg2) {
// TODO Auto-generated method stub

}

@Override
public void beforeNavigateBack(WebDriver arg0) {
// TODO Auto-generated method stub
System.out.println(“Before Navigating Back “+arg0.getCurrentUrl());
}

@Override
public void beforeNavigateForward(WebDriver arg0) {
// TODO Auto-generated method stub

}

@Override
public void beforeNavigateRefresh(WebDriver arg0) {
// TODO Auto-generated method stub

}

@Override
public void beforeNavigateTo(String arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void beforeScript(String arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

@Override
public void onException(Throwable arg0, WebDriver arg1) {
// TODO Auto-generated method stub

}

}

Step 2: Create another Class “ListenerMainClass” and write a script (which ever script you prefer). Below script opens two webpages one after other and navigates backs to the first webpage

Step 3: In the Class “ListenerMainClass“, Create EventFiringWebDriver object and pass driver object as a parameter

Step 4: In the Class “ListenerMainClass“, Create an object of the Class “EventCapture” where we implemented all the methods of WebDriverEventListener to register with EventFiringWebDriver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

package listeners;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;

public class ListenerMainClass {

public static void main (String [] args){
WebDriver driver = new FirefoxDriver();
EventFiringWebDriver eventHandler = new EventFiringWebDriver(driver);
EventCapture eCapture = new EventCapture();
//Registering with EventFiringWebDriver
//Register method allows to register our implementation of WebDriverEventListner to listen to the WebDriver events
eventHandler.register(eCapture);
//navigating to the webpage “www.softwaretestingmaterial.com”
eventHandler.navigate().to(“https://www.softwaretestingmaterial.com/100-software-testing-interview-questions/”);
eventHandler.findElement(By.id(“email”)).sendKeys(“asdsadsa”);
//navigating to the webpage “www.softwaretestingmaterial.com/category/selenium/”
eventHandler.navigate().to(“https://www.softwaretestingmaterial.com/agile-testing-interview-questions/”);
//navigating back to the first page
eventHandler.navigate().back();
eventHandler.quit();
//Unregister allows to detach
eventHandler.unregister(eCapture);
System.out.println(“End of Listners Class”);
}
}

Finally, Execute the “ListenerMainClass” class. Methods in class “EventCapture” are called automatically based on the script. Verify the Output in the console. You could find the logs in the console. The two url’s in the console are just because the implementation of beforeNavigateBack and afterNavigateBack methods.

How To Handle Javascript Alerts/PopUps In Selenium WebDriver
Handling Javascript Alerts/PopUps:

In this post, we see how to handle javascript alerts/popus. Alerts are basically popup boxes that take your focus away from the current browser and forces you to read the alert message. You need to do some action such as accept or dismiss the alert box to resume your task on the browser.

To handle alerts popupswe need to do switch to the alert window and call Selenium WebDriver Alert API methods.

There are two types of alerts.

Windows Based
Web Based/Browser Based

Here in this post, I confine to Java Script Alerts (A.K.A. Browser/Web Based Alerts).

For Windows Based, Please check the below link.

How To Handle Windows Based Pop-ups Using AutoIT (WILL UPDATE SOON)

To handle Browser based Alerts (Web based alert popups), we use Alert Interface. The Alert Interface provides some methods to handle the popups.

While running the WebDriver script, the driver control will be on the browser even after the alert generated which means the driver control will be behind the alert pop up. In order to switch the control to alert pop up, we use the following command :

1

driver.switchTo().alert();

Once we switch the control from browser to the alert window. We can use the Alert Interface methods to do required actions such as accepting the alert, dismissing the alert, get the text from the alert window, writing some text on the alert window etc.,

Let’s see the Alert Interface Methods.

We need to Import a package org.openqa.selenium.Alert to handle the alerts in Selenium.

To get a handle to the open alert:

1

Alert alert = driver.switchTo().alert();

To Click on OK button:

1

alert.accept();

To click on Cancel button.

1

alert.dismiss()

To get the text which is present on the Alert.

1

alert.getText();

To enter the text into the alert box

1

alert.sendkeys(String stringToSend);

To Authenticate by passing the credentials

1

alert.authenticateUsing(Credentials credentials)

Sample Program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

package softwareTestingMaterial;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class AlertInterface {

@Test
public void alertWindow() throws Exception{
System.setProperty(“webdriver.chrome.driver”, “D:\\Selenium Environment\\Drivers\\chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.get(“http://softwaretestingplace.blogspot.com/2017/03/javascript-alert-test-page.html”);
driver.findElement(By.xpath(“//*[@id=’content’]/button”)).click();
Thread.sleep(3000);
Alert alert = driver.switchTo().alert();
String print = alert.getText();
System.out.println(print);
alert.accept();
Thread.sleep(3000);
driver.findElement(By.xpath(“//*[@id=’content’]/button”)).click();
Thread.sleep(3000);
alert.dismiss();
driver.close();
}
}

If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.

Stale Element Reference Exception in Selenium Webdriver | StaleElementReferenceException
Stale Element Reference Exception in Selenium Webdriver

In this post, we see causes of Stale Element Reference Exception and how to overcome StaleElementReferenceException in Selenium WebDriver.

1. What is StaleElementReferenceException
2. Causes of Stale Element Reference Exception
3. How To Overcome Stale Element Reference Exception in Selenium

What is StaleElementReferenceException:

Stale means old, decayed, no longer fresh. Stale Element means an old element or no longer available element. Assume there is an element that is found on a web page referenced as a WebElement in WebDriver. If the DOM changes then the WebElement goes stale. If we try to interact with an element which is staled then the StaleElementReferenceException is thrown.

Causes of Stale Element Reference Exception:

A stale element reference exception is thrown in one of two cases, the first being more common than the second.

The two reasons for Stale element reference are

The element has been deleted entirely.
The element is no longer attached to the DOM.

We face this stale element reference exception when the element we are interacting is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference to the element.

How To Overcome Stale Element Reference Exception in Selenium:

Here, I will show you some ways to overcome StaleElementReferenceException. You could also refer the official Selenium post

Solution 1:

You could refresh the page and try again for the same element.

Assume you are trying to click on a link and getting the stale element exception.

Sample code to overcome the issue

1
2

driver.navigate().refersh();
driver.findElement(By.xpath(“xpath here”)).click();

Solution 2:

If an element is not attached to DOM then you could try using ‘try-catch block’ within ‘for loop’

1
2
3
4
5
6
7
8
9
10
11

// Using for loop, it tries for 3 times.
// If the element is located for the first time then it breaks from the for loop nad comeout of the loop
for(int i=0; i<=2;i++){
try{
driver.findElement(By.xpath(“xpath here”)).click();
break;
}
catch(Exception e){
Sysout(e.getMessage());
}
}

Solution 3:

1

wait.until(ExpectedConditions.presenceOfElementLocated(By.id(“table”)));

Use ExpectedConditions.refreshed to avoid StaleElementReferenceException and retrieve the element again. This method updates the element by redrawing it and we can access the referenced element.

1

wait.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf(“table”)));

Solution 4:

We can handle Stale Element Reference Exception by using POM.

We could avoid StaleElementException using POM. In POM, we use initElements() method which loads the element but it won’t initialize elements. initElements() takes latest address. It initializes during run time when we try to perform any action on an element. This process is also known as Lazy Initialization.

If you find any other solution to overcome StaleElementException, you could post your solution in the comments section below.

Sikuli Guide For Beginners – Integrate Sikuli With Selenium | Software Testing Material

In this article, we will see Sikuli Graphical User Interface Automation Tool in detail and how to integrate Sikuli with Selenium.

Introduction To Sikuli Tool:

Sikuli is a Graphical User Interface Automation Tool. Using Sikuli Automation tool we could automate whatever we see on the screen. It basically uses image recognition technology to identify and control GUI elements. We all know that using Selenium we cant automate windows objects. Integrating Sikuli with Selenium allows us to overcome this issue. Using Sikuli with Selenium, we could automate windows objects. Using Sikuli we could automate both Web and Windows based applications. Most of us using AutoIT to upload or download files in Selenium. Using Sikuli you could do it very easily. We could do flash testing using Selenium. We could not identify the element locators of flash objects. We could use sikuli tool to automate flash objects.

Mechanism of Sikuli with Selenium:

The object, if we want to automate, should be captured and placed in a specific folder and pass the path of the appropriate image into our Selenium script. At the time of execution, if the image which we passed is matched with the image on the screen then the desired action will be performed on that object.

Advantages of Sikuli Graphical User Interface Tool:
It is an open source tool for automation
Easily to integrate sikuli with selenium
Can automate Desktop / Windows application
Easily automate Flash objects – Flash Testing
It can be used on any platform such as Windows/Linux/Mac/Mobile
Due to its image recognition technique, we could automate even though there is no access to the code. It allows us to automate anything we see on the screen.
Sikuli Setup To Integrate Sikuli with Selenium:

To integrate sikuli with selenium, we need to follow the below steps.

Step 1: Download Sikuli jars

Step 2: Double-click on “sikulixsetup-1.1.1.jar” to do setup.

After having installed Sikuli on your system, a jar file “sikulixapi.jar” generate.

Step 3: Open Eclipse IDE and create a project

Here is a post on how to do Selenium setup.

Step 4: Include “sikulixapi.jar”

Right click on project – Go to Build path – libraries tab – click on ‘Add external jars’ and add the following jar file and click on OK.

Add this “sikulixapi.jar” file

I will present two sample scripts to show you how sikuli works in real time.

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

Scripts to Integrate Sikuli with Selenium Webdriver:

Script 1: Facebook login Using Sikuli with Selenium

Our goal based on the below program is to open facebook page and pass user credentials and do login.

Step 1: Open facebook login page
Step 2: I have captured the following images from facebook login page and saved on my local drive.

Note: You could find the detailed explanation of the script in the code snippet below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

package softwareTestingMaterial;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
import org.testng.annotations.Test;

public class STMSikuliClass {

@Test
public void facebookLogin() throws FindFailed{

// Creating Object of ‘Screen’ class
//Screen is a base class provided by Sikuli. It allows us to access all the methods provided by Sikuli.
Screen screen = new Screen();
// Creating Object of Pattern class and specify the path of specified images
// I have captured images of Facebook Email id field, Password field and Login button and placed in my local directory
// Facebook user id image
Pattern username = new Pattern(“C:\\Users\\admin\\Desktop\\Sikuli Images For Selenium\\FacebookEmail.png”);
// Facebook password image
Pattern password = new Pattern(“C:\\Users\\admin\\Desktop\\Sikuli Images For Selenium\\FacebookPassword.png”);
// Facebook login button image
Pattern login = new Pattern(“C:\\Users\\admin\\Desktop\\Sikuli Images For Selenium\\FacebookLogin.png”);
// Initialization of driver object to launch firefox browser
System.setProperty(“webdriver.gecko.driver”, System.getProperty(“user.dir”)+”\\src\\drivers\\geckodriver.exe”);
WebDriver driver = new FirefoxDriver();
// To maximize the browser
driver.manage().window().maximize();
// Open Facebook
driver.get(“https://en-gb.facebook.com/”);
screen.wait(username, 10);
// Calling ‘type’ method to enter username in the email field using ‘screen’ object
screen.type(username, “softwaretestingmaterial@gmail.com”);
// Calling the same ‘type’ method and passing text in the password field
screen.type(password, “softwaretestingmaterial”);
// This will click on login button
screen.click(login);
}

}

Script 2: Actions using Sikuli with Selenium

Step 1: Open softwaretestingmaterial.com
Step 2: I have captured the below mentioned image and saved on my local drive.

Our goal based on the below program is to open softwaretestingmaterial page and do actions such as click, doubleClick, rightClick.

Note: You could find the detailed explanation of the script in the code snippet below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

package softwareTestingMaterial;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
import org.testng.annotations.Test;

public class STMActions {

@Test
public void runSikuli() throws FindFailed{
Screen screen = new Screen();

System.setProperty(“webdriver.gecko.driver”, System.getProperty(“user.dir”)+”\\src\\drivers\\geckodriver.exe”);

WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(“https://www.softwaretestingmaterial.com”);

Pattern pattern = new Pattern(“C:\\Users\\admin\\Desktop\\Sikuli Images For Selenium\\ManualTesting.png”);
//uncomment below statement to do ‘left click’ on Manual Testing tab
//screen.click(pattern);
//uncomment below statement to do ‘double click’ on Manual Testing tab
//screen.doubleClick(pattern);
//uncomment below statement to do ‘right click’ on Manual Testing tab
//screen.rightClick(pattern);

}

}
Sikuli Methods:

Here to showcase some examples, I am going to use the same object of Screen class which I have taken in the above scripts.

Click on an element: screen.click(“path of your image”);
Double click on an element: screen.doubleClick(“path of your image”);
Right click on an element: screen.rightClick(“path of your image”);
Type on a text box: screen.type(“path of your image”, “Your text message”);
To find an element: screen.find(“path of your image”);
Element identification whether it exists or not: screen.exists(“path of your image”);
Drag and drop: screen.dragDrop(“path of your Source image”,”path of your Target image”);

To learn more on Sikuli, please refer this offical documentation.  I am concluding here on “Sikuli Tutorial for begineers”, If you have any questions, please comment below.

Headless Browser Testing using Selenium WebDriver | Software Testing Material
Headless Browser Testing using Selenium WebDriver

In this post, we learn what is Headless Browser Testing and what we could achieve with Headless Browser Testing using Selenium WebDriver. Selenium WebDriver is a tool to automate web applications. It verifies that the web applications are working as expected. It supports many browsers such as Mozilla Firefox, Google Chrome, Internet Explorer, Safari etc., You could open these browsers manually and you could see the graphical user interface of above mentioned browsers.

If you execute a Selenium script using “WebDriver driver = new FirefoxDriver();”, then you could see Firefox browser Graphical User Interface (GUI) in your system and a result based on your script in your IDE console.

Hope you have seen above mentioned browsers earlier. If you want to see how to use these browsers then check these links.

Mozilla Firefox – GeckoDriver
Google Chrome
Internet Explorer
Edge Driver

So what is Headless Browser?

Now coming to the headless browser, a headless browser is a browser which doesn’t have a GUI. Headless browser is used to simulate programs even though there is no browser installed on your local system. You couldn’t see any browser in your system but you will get the same result in your console. Headless browser doesn’t have GUI means it’s just that it doesn’t have any GUI but the program runs in the background.

Headless Browser Testing Using Selenium WebDriver:

Headless browser testing using Selenium WebDriver is done to test the application without any visual interruption.

Two widely used headless drivers with practical examples.

Advantages of Performing Headless Browser Testing In Selenium:

It’s faster. The performance is better compared to browser automation. Automated testing is to automate a browser to ensure that the application is running as expected. Running regression scripts take lots of time. With headless browsers, we could save time.
It enables you to run the scripts on a system which doesn’t have a browser.
Imagine you have a situation to run some tests on a version of google chrome and there is no such version of google chrome on your local system. In this case, you could use the headless browser, most of the headless browsers support browser versions.

Disadvantages of Headless Browsers Testing:

Debugging is a bit difficult using headless browsers. Here browser is not visible, the only way is to capture a screenshot.

In the next post, we will learn how to perform HtmlUnitDriver headless browser testing using Selenium WebDriver and PhanthomJsDriver headless browser testing using Selenium WebDriver.

As always, feel free to share this post with your friends and colleagues on Facebook, Twitter, and Google Plus!

Headless Browser Testing Using HtmlUnitDriver in Selenium WebDriver
Headless Browser Testing Using HtmlUnitDriver In Selenium WebDriver

In the earlier post, we have given a brief explanation on what is headless browser and in this post, we learn how to perform headless browser testing using HtmlUnitDriver in Selenium WebDriver. HtmlUnitDriver is one of the drivers of Selenium WebDriver. HtmlUnitDriver and PhatomJsDriver are most popular headless browsers.

You could download HtmlUnitDriver Jar file from here. – Selenium HtmlUnit Driver

Html Unit Driver is currently the fastest and most lightweight implementation of WebDriver. As the name suggests, this is based on HtmlUnit. HtmlUnit is a java based implementation of a web browser without a GUI. HtmlUnit Driver is a well known Headless Browser driver. HtmlUnit Driver is similar to the other drivers such as Mozilla Firefox, Google Chrome, Internet Explorer but you couldn’t see the GUI of Html UnitDriver.

You can create a HtmlUnitWebDriver as shown below

1

WebDriver driver = new HtmlUnitDriver()

Advantages of HtmlUnitDriver are:

Fastest implementation of WebDriver compared to other browsers
A pure Java solution and so it is platform independent.
Supports JavaScript
It allows you to choose other browser versions to run your scripts.

Usually, to run Selenium Scripts using Firefox, we initialize the Firefox driver.

1

WebDriver driver = new FirefoxDriver();

Whereas while running Selenium Scripts using HtmlUnitDriver you need to write the below statement

1

WebDriver driver = new HtmlUnitDriver();

Remaining statements in your script will be as usual.

Let’s see a working example on HtmlUnitDriver in Selenium WebDriver.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.testng.annotations.Test;

public class HeadlessBrowser {

@Test
public void htmlUnitDriver() throws Exception{
// To declare and initialize HtmlUnitDriver
WebDriver driver = new HtmlUnitDriver();
//WebDriver driver = new HtmlUnitDriver(BrowserVersion.)
// Set implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Open “Google.com and search SoftwareTestingMaterial.com”
driver.get(“https://www.google.com”);
WebElement element = driver.findElement(By.name(“q”));
element.sendKeys(“softwaretestingmaterial.com”);
element.submit();
//Click on Software Testing Material link
driver.findElement(By.linkText(“Software Testing Material”)).click();
// Get the title of the site and store it in the variable Title
String Title = driver.getTitle();
// Print the title
System.out.println(“I am at ” +Title);
}
}

Output:

1
2
3
4
5
6
7
8
9
10
11
12

I am at Software Testing Material – A Site for Software Testers
PASSED: htmlUnitDriver

===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

JavaScript In HtmlUnit Driver:

HtmlUnitDriver uses Rhino JavaScript engine. Other browsers are using separate JavaScript engine. So the test results may differ when compared to other browsers when you test JavaScript applications using HtmlUnit. By default, JavaScript is disabled in HtmlUnitDriver. Don’t worry, there is a way to enable it. J

It’s very easy to enable JavaScript support. We could enable JavaScript in HtmlUnitDriver in two ways

1. Enabling JavaScript while initializing the HtmlUnitDriver

1

HtmlUnitDriver driver = new HtmlUnitDriver(true);

2. Setting ‘setJavascriptEnabled’ to true

1
2

HtmlUnitDriver driver = new HtmlUnitDriver();
setJavascriptEnabled(true);

None of the popular browsers use the JavaScript engine used by HtmlUnit (Rhino). If you test JavaScript using HtmlUnit the results may differ significantly from those browsers.

Different Browser Versions using HtmlUnitDriver:

We could test our scripts on different browser versions using HtmlUnitDriver. Yes, it allows us to choose our preferred browser version. See the below screenshot.

1

WebDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3);

I am concluding this post about headless browser testing using HtmlUnitDriver. In the next post, we will learn how to perform headless browser testing using PhanthomJSDriver in Selenium WebDriver.

As always, feel free to share this post with your friends and colleagues on Facebook, Twitter, and Google Plus!

Headless Browser Testing Using PhantomJSDriver in Selenium WebDriver
Headless Browser Testing Using PhantomJSDriver In Selenium WebDriver

In the earlier post, we have seen some brief explanation on what is headless browser and in this post, we learn how to perform headless browser testing using PhantomJSDriver in Selenium WebDriver. PhantomJSDriver is one of the drivers of Selenium WebDriver. HtmlUnitDriver and PhantomJSDriver are most popular headless browsers.

PhantomJS is used for Headless Browser Testing of Web Applications that comes with in-built GhostDriver. This means that the rendered web pages are never actually displayed.

Advantages:

Lightweight
Proxy server support
Fastest implementation of WebDriver
Platform Independent
Allows us to simulate different browsers having different versions.

You could download PhantomJSDriver executable file from here – PhantomJS Driver

Download PhantomJSDriver jar file from here – PhantomJS Jars

Usually, to run Selenium Scripts using Firefox, we initialize the Firefox driver.

1

WebDriver driver = new FirefoxDriver();

Whereas while running Selenium Scripts using PhantomJSDriver you need to write the below statement

1

WebDriver driver = new PhantomJSDriver ();

Remaining statements in your script will be as usual.

Let’s see a working example using PhantomJSDriver in Selenium WebDriver:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.testng.annotations.Test;

public class HeadlessBrowser {

@Test
public void phantomJSDriver() throws Exception{
//Set the path of the phantomjs.exe file in the properties
System.setProperty(“phantomjs.binary.path”, “D:\\Selenium\\Drivers\\phantomjs.exe”);
// To declare and initialize PhantomJSDriver
WebDriver driver = new PhantomJSDriver();
// Download link is http://phantomjs.org/download.html
// Set implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Open “Google.com and search SoftwareTestingMaterial.com”
driver.get(“https://www.google.com”);
// To locate the searchbox using its name
WebElement element = driver.findElement(By.name(“q”));
// To enter text “softwaretestingmaterial.com”
element.sendKeys(“softwaretestingmaterial.com”);
// To submit
element.submit();
//Click on Software Testing Material link
driver.findElement(By.linkText(“Software Testing Material”)).click();
// Get the title of the site and store it in the variable Title
String Title = driver.getTitle();
// Print the title
System.out.println(“I am at ” +Title);
}
}

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13

I am at Software Testing Material – A Site for Software Testers
PASSED: phantomJSDriver

===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

Different Browser Versions using PhanthomJSDriver:

We could test our scripts on different browser versions using PhanthomJSDriver. Yes, it allows us to choose our preferred browser version. See the below screenshot.

1

WebDriver driver = new PhanthomJSDriver(BrowserVersion.FIREFOX_3);

I am concluding this post about headless browser testing using PhanthomJSDriver. Check out our other post on how to perform headless browser testing using HtmlUnitDriver in Selenium WebDriver.

As always, feel free to share this post with your friends and colleagues on Facebook, Twitter, and Google Plus!

WhatsApp us