0% found this document useful (0 votes)
154 views190 pages

Selenium Wings 1 Notes ( - 1)

Selenium sample

Uploaded by

LATHIKA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
154 views190 pages

Selenium Wings 1 Notes ( - 1)

Selenium sample

Uploaded by

LATHIKA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 190

JunitJ

Unit is an open source Unit Testing Framework for JAVA. It is useful for Java Developers to write and run
repeatable tests. Erich Gamma and Kent Beck initially develop it. It is an instance of xUnit architecture.
As the name implies, it is used for Unit Testing of a small chunk of code.

Developers who are following test-driven methodology must write and execute unit test first before any
code.

Once you are done with code, you should execute all tests, and it should pass. Every time any code is
added, you need to re-execute all test cases and makes sure nothing is broken.

• You need to use annotations in spite of special method name as before.


• Instead of using setup method, you need to use @before annotation.
• Instead of using teardown method, put @after annotation.
• Instead of using testxxxx before method name, use @test annotation.

https://www.guru99.com/junit-tutorial.html

Setup
@Before annotation in JUnit is used on a method containing Java code to run before each test case. i.e it
runs before each test execution.

Teardown (regardless of the verdict)


@After annotation is used on a method containing java code to run after each test case. These methods
will run even if any exceptions are thrown in the test case or in the case of assertion failures.

S.No. Annotations Description


This annotation is a replacement of
org.junit.TestCase which indicates that public
1. @Test
void method to which it is attached can be
executed as a test Case.
This annotation is used if you want to
2. @Before execute some statement such as
preconditions before each test case.
This annotation is used if you want to
execute some statements before all the test
3. @BeforeClass
cases for e.g. test connection must be
executed before all the test cases.
This annotation can be used if you want to
execute some statements after each Test
4. @After
Case for e.g resetting variables, deleting
temporary files ,variables, etc.
This annotation can be used if you want to
execute some statements after all test cases
5. @AfterClass
for e.g. Releasing resources after executing
all test cases.
S.No. Annotations Description
This annotation can be used if you want to
ignore some statements during test
6. @Ignores
execution for e.g. disabling some test cases
during test execution.
This annotation can be used if you want to
set some timeout during test execution for
7. @Test(timeout=500) e.g. if you are working under some SLA
(Service level agreement), and tests need to
be completed within some specified time.
This annotation can be used if you want to
handle some exception during test execution.
8. @Test(expected=IllegalArgumentException.class) For, e.g., if you want to check whether a
particular method is throwing specified
exception or not.

Junit 4 to 5
added/updated tags in
Junit5 description
Parameterized tests make it possible to run a test multiple times with different
arguments. They are declared just like regular @Test methods but use the
@ParameterizedTest annotation instead.

In addition, you must declare at least one source that will provide the
arguments for each invocation and then consume the arguments in the test
method.

For example, the following example demonstrates a parameterized test that


@ParameterizedTest@ uses the @ValueSource annotation to specify a String array as the source of
Value Source arguments.
JUnit 5 has the ability to repeat a test a specified number of times simply by
annotating a method with @RepeatedTest and specifying the total number of
repetitions desired.

Each invocation of a repeated test behaves like the execution of a regular


@RepeatedTest @Test method.
We can use this annotation to declare tags for filtering tests, either at the class
@tag or method level.
Test classes and test methods can declare custom display names that will be
@displayname displayed by test runners and test reports.
The @Disabled annotation is used to disable or skip tests at class or method
@Disabled level. This is analogous to JUnit 4’s @Ignore.
As you can see from the result of the test, when i==3, the test passes, otherwise it fails.
https://devqa.io/junit-5-annotations/

Error Collector

Why use Error Collector?


While writing a test script, you want to execute all the tests even if any line of code fails due to network
failure, assertion failure, or any other reason. In that situation, you can still continue executing test script
using a special feature provided by JUnit known as “error collector.”

For this, JUnit uses @Rule annotation which is used to create an object of error collector. Once the
object for error collector is created, you can easily add all the errors into the object using
method addError (Throwable error). As you know, that Throwable is the super class
of Exception and Error class in Java. When you add errors in this way, these errors will be logged in
JUnit test result .

The benefit of adding all errors in an Error Collector is that you can verify all the errors at once. Also, if the
script fails in the middle, it can still continue executing it

TestNg

https://www.guru99.com/all-about-testng-and-selenium.html

What is TestNG?
`
Using TestNG, you can generate a proper report, and you can easily come to know how many test cases
are passed, failed, and skipped. You can execute the failed test cases separately.

For example:

• Suppose, you have five test cases, one method is written for each test case (Assume that the
program is written using the main method without using testNG). When you run this program first,
three methods are executed successfully, and the fourth method is failed. Then correct the errors
present in the fourth method, now you want to run only fourth method because first three methods
are anyway executed successfully. This is not possible without using TestNG.
• The TestNG in Selenium provides an option, i.e., testng-failed.xml file in test-output folder. If you
want to run only failed test cases means you run this XML file. It will execute only failed test
cases.

Main Advantages over Junit:

-Reporting

-Grouping test case using xml file and prioritizing them


-The same test case can be executed multiple times without loops just by using keyword called
‘invocation count.’

-cross browser testing

-The TestNG framework can be easily integrated with tools like TestNG Maven, Jenkins, etc.

Uncaught exceptions are automatically handled by TestNG without terminating the test prematurely.
These exceptions are reported as failed steps in the report.

Advantages of TestNG over JUnit


There are three major advantages of TestNG over JUnit:

• Annotations are easier to understand


• Test cases can be grouped more easily
• Parallel testing is possible

Notice the following.

• TestNG does not require you to have a main () method.


• Methods need not be static.
• We used the @Test annotation. @Test is used to tell that the method under it is a test case. In
this case, we have set the verifyHomepageTitle() method to be our test case, so we placed an
‘@Test’ annotation above it.
• Since we use annotations in TestNG, we needed to import the package
org.testng.annotations.*.
• We used the Assert class. The Assert class is used to conduct verification operations in TestNG.
To use it, we need to import the org.testng.Assert package.
• Reports are created under test-output folder.

Parameters in test NG:

Parameters
Number 0 has the highest priority (it’ll be executed first) and the priority goes on based on the given
number i.e., 0 has the highest priority than 1. And 1 has the highest priority than 2 and so on.

If you want the methods to be executed in a different order, use the parameter “priority”. Parameters are
keywords that modify the annotation’s function.
Methods with Same Priority:
There may be a chance that methods may contain same priority. In those cases, testng considers the
alphabetical order of the method names whose priority is same.

• Parameters require you to assign a value to them. You do.this by placing a “=” next to them, and
then followed by the value.
• Parameters are enclosed in a pair of parentheses which are placed right after the annotation like
the code snippet shown below.

TestNG will execute the @Test annotation with the lowest priority value up to the largest. There is no
need for your priority values to be consecutive.

Multiple Parameters: **
Aside from “priority,” @Test has another parameter called “alwaysRun” which can only be set to either
“true” or “false.” To use two or more parameters in a single annotation, separate them with a
comma such as the one shown below.

Combining both prioritized (having same priority) and non-prioritized methods:


In this case, we’ll cover two cases in one testng class.

***non priority value goes first**

1. Methods having same priority value.


2. More than one non-prioritized methods.

package com.guru.testngannotations;

import org.testng.annotations.Test;

public class TestNG_Priority_Annotations {


@Test()
public void c_method(){
System.out.println("I'm in method C");
}
@Test()
public void b_method(){
System.out.println("I'm in method B");
}
@Test(priority=6)
public void a_method(){
System.out.println("I'm in method A");
}
@Test(priority=0)
public void e_method(){
System.out.println("I'm in method E");
}
@Test(priority=6)
public void d_method(){
System.out.println("I'm in method D");
}
}
Output:

I'm in method B
I'm in method C
I'm in method E
I'm in method A
I'm in method D
PASSED: b_method
PASSED: c_method
PASSED: e_method
PASSED: a_method
PASSED: d_method
Explanation:

First preference: Non-prioritized methods: ‘c’ and ‘b’: Based on alphabetical order ‘b’ was executed first
and then ‘c’.

Second preference: Prioritized methods: ‘a’, ‘e’ and ‘d’: ‘e’ was executed first as it was having highest
priority(0). As the priority of ‘a’ and ‘d’ methods were same, testng considered the alphabetical order of
their methods names. So, between them, ‘a’ was executed first and then ‘d’

Negative Values in Priority Field:

Analyzing Test Sequence with Test Priority In TestNG with Selenium

The below-given code is the same as the code we used above. But this time, I have reassigned the
priorities of all the methods.

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

public class TestNG {


7 WebDriver driver = new ChromeDriver();

@Test (priority = 0)
public void CloseBrowser() {
driver.close();
System.out.println("Closing Google Chrome browser");
}

@Test (priority = -1)


public void OpenBrowser() {
System.out.println("Launching Google Chrome browser");
driver.get("https://www.demoqa.com");
}

@Test
public void AccountTest(){
System.out.println("Some tests for Customer Account");
}
}
In the above test code, the method OpenBrowser contains priority as -1, CloseBrowser as 0, and no
priority assignment happens to AccountTest. Let's see the output after running the above selenium code
in Eclipse.

Looking at the output of this test code, we prove three main points in TestNG priority:

1. We can assign negative priorities to a method.


2. With a method with no priority, the priority is set to 0 by default.

Observe that the AccountTest method ran before CloseBrowser even without having any priority because
both sets to priority = 0, and hence, they run alphabetically.

Hence, we can change the sequence of tests in TestNG using priorities.

Case-sensitive in TestNG
Just for your information there is a standard syntax for defining priority in testNG i.e. @Test
(priority=4), suppose you are defining it in some other syntax say @Test (PRIORITY=1) then your IDE
will show it as a compilation error. Refer image below:

Annotations:

Summary of TestNG Annotations


@BeforeSuite: The annotated method will be run before all tests in this suite have run.

@AfterSuite: The annotated method will be run after all tests in this suite have run.

@BeforeTest: The annotated method will be run before any test method belonging to the classes inside
the tag is run.

@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside
the tag have run.

@BeforeGroups: The list of groups that this configuration method will run before. This method is
guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.

@AfterGroups: The list of groups that this configuration method will run after. This method is guaranteed
to run shortly after the last test method that belongs to any of these groups is invoked.

@BeforeClass: The annotated method will be run before the first test method in the current class is
invoked.

@AfterClass: The annotated method will be run after all the test methods in the current class have been
run.

@BeforeMethod: The annotated method will be run before each test method.

@AfterMethod: The annotated method will be run after each test method.

@Test: The annotated method is a part of a test case.

- Before test is executed only once.

Difference between before method and before test:


Parallel Testing:

Parallel Testing is a software testing type in which multiple versions or subcomponents of an application
are tested with same input on different systems simultaneously to reduce test execution time. The
purpose of parallel testing is finding out if legacy version and new version are behaving the same or
differently and ensuring whether new version is more efficient or not.
The below image demonstrates the parallel testing.

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >


<suite name = "Parallel Testing Suite">
<test name = "Parallel Tests" parallel = "methods">
<classes>
<class name = "ParallelTest" />
</classes>
</test>
</suite>
? Design the test cases done

? Prioritizing the test cases - done

? Disabling the test cases either at class level or in testing. Xml

https://www.javatpoint.com/exclude-include-test-cases-in-testng

Disabling using annotation parameter:

Sometimes, it happens that our code is not ready and the test case written to test that method/code fails.
In such cases, annotation @Test (enabled = false) helps to disable this test case.

If a test method is annotated with @Test (enabled = false), then the test case that is not ready to test is
bypassed.

Create Test Case Class


• Create a java test class, say, IgnoreTest.java in /work/testng/src.
• Add test methods, testPrintMessage(), and, testSalutationMessage(), to your test class.
• Add an Annotation @Test(enabled = false) to the method testPrintMessage().

Disabling using xml file

https://www.javatpoint.com/exclude-include-test-cases-in-testng

- If we want to disable the MobileLoginCarLoan test case in car loan module, then we need to add
the <method> tag in xml file which has access to all the methods of a class.
- Run the testng.xml file. Right click on the testng.xml file, and move the cursor down, you will
see the Run As and then click on the 1 TestNG Suite.

XML format

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="loan_department">
<test name="Personal_loan">
<classes>
<class name="day1.module1"/>
</classes>
</test> <!-- Test -->
<test name="Car_loan">
<classes>
<class name="day1.module2">
<methods>
<exclude name = "MobileLoginCarLoan"/>
</methods>
</class>
</classes>
</test>
</suite> <!-- Suite -->

Including Test cases:

Note: Suppose we have multiple test cases and you want to include only one or two test cases, in such
situation, we use <include> tag. If we use the <exclude> tag, then it becomes very tedious to exclude all
the test cases.

Let's understand through an example of <include> tag.

testng.xml file

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="test_suite">
<test name="test">
<classes>
<class name="day1.test">
<methods>
<include name="test3"/>
</methods>
</class>
</classes>
</test> <!-- Test -->

</suite> <!-- Suite -->

Running one specific test cases number of times:

TestNG supports multi-invocation of a test method, i.e., a @Test method can be invoked multiple times
sequentially or in parallel. If we want to run single @Test 10 times at a single thread,
then invocationCount can be used.
To invoke a method multiple times, the keyword invocationCount = <int> is required. For example −
@Test(invocationCount = 10)
In this example, the @Test method will execute for 10 times each on a single thread.
In this article, we will illustrate how to get the current invocation count.
Approach/Algorithm to solve this problem
• Step 1 − Create a TestNG class, NewTestngClass.
• Step 2 − Write two @Test methods in the class NewTestngClass as shown in the programming
code section below. Add invocationCount=10
• Step 3 − Create the testNG.xml as given below to run the TestNG classes.
• Step 4 − Now, run the testNG.xml or directly testNG class in IDE or compile and run it using
command line.
• Step 5 − In the output, the user can see a total of 1 thread running sequentially for all invocations
of @Test.

? Running collections of all test cases in testing.xmlMaven

Customized report testng/junit?

https://www.guru99.com/pdf-emails-and-screenshot-of-test-reports-in-selenium.html

How to skip a test in test NG?

https://www.tutorialspoint.com/how-to-use-testng-skipexception

https://www.seleniumeasy.com/testng-tutorials/skip-test-in-testng

Following are the ways to skip a @Test execution −


• Use the parameter enabled=false at @Test. By default, this parameter is set as True.
• Use throw new SkipException(String message) to skip a test.
• Conditional Skip − The user can have a condition check. If the condition is met, it will
throw SkipException and skip the rest of the code.

TestNG Groups
https://www.javatpoint.com/testng-groups
TestNG Groups allow you to perform groupings of different test methods. Grouping of test methods is
required when you want to access the test methods of different classes.

Not only you can declare the methods within a specified group, you can also declare another group within
a specified group. Thus, TestNG can be asked to include a certain set of groups while excluding another
set of groups.

It provides you maximum flexibility by partitioning your test methods in groups and does not require
recompilation of test cases if you run your two different sets of test cases back to back.

Groups are specified in the testng.xml file with <groups> tag. Groups can be specified either in the
<suite> tag or <test> tag. If the <groups> tag is specified inside the <suite> tag, then it is applied to all the
<test> tags of XML file. If the <groups> tag is specified within a particular <test> folder, then it is applied
to that particular <test> tag only.

Eg:

1. @Test(groups= {"SmokeTest"})
2. public void MobileLoginHomeLoan()
3. {
4. System.out.println("Mobile Login Home Loan");
5. }

Xml eg for groups:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="test_suite">
<groups>
<run>
<include name="SmokeTest"/>
</run>
</groups>
<test name="Personal Loan">
<classes>
<class name="com.javatpoint.Personal_loan"/>
</classes>
</test> <!-- Test -->
<test name="Home Loan">
<classes>
<class name="com.javatpoint.Home_loan"/>
</classes>
</test> <!-- Test -->
<test name="Car Loan">
<classes>
<class name="com.javatpoint.Car_loan"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Output:
Tests belonging to multiple Groups

Example:

@Test(groups= {"Group A"})


public void testcase1()
{
System.out.println("Test case belonging to Group A");
}
@Test(groups= {"Group A","Group B"})
public void testcase2()
{
System.out.println("Test case belonging to both Group A and Group B");
}
@Test(groups= {"Group B"})
public void testcase3()
{
System.out.println("Test case belonging to Group B");
}

Xml example:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="test_suite">
<test name="Group A">
<groups>
<run>
<include name="Group A"/>
</run>
</groups>
<classes>
<class name="com.javatpoint.Groups"/>
</classes>
</test> <!-- Test -->
<test name="Group B">
<groups>
<run>
<include name="Group B"/>
</run>
</groups>
<classes>
<class name="com.javatpoint.Groups"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Run the testng.xml file by clicking right click on the testng.xml file.

Output:
Including/Excluding Groups

Is accomplished using normal naming conventions of the test case name and then in the xml file use-
<include name="Include Group"/>
<exclude name="Exclude Group"/>

{
@Test(groups= {"Include Group"})
public void test_case1()
{
System.out.println("This is test case 1");
}
@Test(groups= {"Include Group"})
public void test_case2()
{
System.out.println("This is test case 2");
}
@Test(groups= {"Exclude Group"})

public void test_case3()


{
System.out.println("This is test case 3");
}
}
Test NG example:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="test_suite">
<test name="Include and Exclude Group">
<groups>
<run>
<include name="Include Group"/>
<exclude name="Exclude Group"/>
</run>
</groups>
<classes>
<class name="com.javatpoint.Groups"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Output:\
Groups using Using Regular Expressions
Eg:
@Test(groups= {"Include test case1"})
public void test_case1()
{
System.out.println("This is test case 1");
}
@Test(groups= {"Include test case2"})
public void test_case2()
{
System.out.println("This is test case 2");
}
@Test(groups= {"Exclude test case3"})
public void test_case3()
{
System.out.println("This is test case 3");
}
}
Xml eg:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="test_suite">
<test name="Including test cases">
<groups>
<run>
<include name="Include.*"/>
</run>
</groups>
<classes>
<class name="com.javatpoint.Regular_Expression"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
Output:

Example 2:

How To Exclude/Include Test Cases with Groups?


TestNG Groups also provides provision to ignore test scenario(s)/test methods using the <exclude>
tag in the <methods> section. On similar lines, the <include> tag in the <methods> section of
testng.xml is used for including the test methods as a part of the test execution process.

TestNG_SearchGroup class: To run test methods whose name includes “.*Bing.*” and exclude test
method(s) whose name contains “.*Google.*”, we use method groups in the following manner:

1<class name="org.testnggroup.TestNG_SearchGroup">
2 <methods>
3 <include name=".*Bing.*"/>
4 <exclude name=".*Google.*"/>
5 </methods>
6</class>
Groups in Groups

We can also specify a group within another group. The groups which are defined in other groups are
known as Meta Groups

/** using define tag in the testng.xml file

Eg:
{
@Test(groups= {"Smoke"})
public void test1()
{
System.out.println("test1");
}
@Test(groups= {"Regression"})
public void test2()
{
System.out.println("test2");
}
@Test
public void test3()
{
System.out.println("test3");
}
Xml example:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="test_suite">
<test name="Groups in Groups">
<groups>
<define name="Group 1">
<include name="Smoke"/>
<include name="Regression"/>
</define>
<run>
<include name="Group 1"/>
</run>
</groups>
<classes>
<class name="com.javatpoint.Groups_in_Groups"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
Output:

https://www.tutorialspoint.com/testng/testng_ignore_test.htm

DependsOn methods

Sometimes, you may need to invoke methods in a test case in a particular order, or you may want to
share some data and state between methods. This kind of dependency is supported by TestNG, as it
supports the declaration of explicit dependencies between test methods.
TestNG allows you to specify dependencies either with −
• Using attribute dependsOnMethods in @Test annotations, OR.
• Using attribute dependsOnGroups in @Test annotations.

Eg:

Create Test Case Class


• Create a java test class, say, DependencyTestUsingAnnotation.java in /work/testng/src.
• Add test methods, testPrintMessage() and testSalutationMessage(), and initEnvironmentTest(), to
your test class.
• Add attribute dependsOnMethods = {"initEnvironmentTest"} to the @Test annotation
of testSalutationMessage() method.
Following are the DependencyTestUsingAnnotation.java contents.

import org.testng.Assert;
import org.testng.annotations.Test;

public class DependencyTestUsingAnnotation {


String message = "Manisha";
MessageUtil messageUtil = new MessageUtil(message);

@Test
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
message = "Manisha";
Assert.assertEquals(message, messageUtil.printMessage());
}

@Test(dependsOnMethods = { "initEnvironmentTest" })
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Manisha";
Assert.assertEquals(message, messageUtil.salutationMessage());
}

@Test
public void initEnvironmentTest() {
System.out.println("This is initEnvironmentTest");
}
}
Create testng.xml
Create testng.xml in /work/testng/src to execute test case(s).

<?xml version = "1.0" encoding = "UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name = "Suite1">


<test name = "test1">
<classes>
<class name = "DependencyTestUsingAnnotation" />
</classes>
</test>
</suite>

Verify the output.


This is initEnvironmentTest
Inside testPrintMessage()
Manisha
Inside testSalutationMessage()
Hi!Manisha

===============================================
Suite1
Total tests run: 3, Failures: 0, Skips: 0
===============================================

dependsOnGroups
Create Test Case Class
• Create a java test class, say, DependencyTestUsingAnnotation.java.
• Add test methods, testPrintMessage() testSalutationMessage(), and initEnvironmentTest() to your
test class, and add them to the group "init".
• Add the attribute dependsOnMethods = {"init.*"} to the @Test annotation
of testSalutationMessage() method.
Create a java class file named DependencyTestUsingAnnotation.java in /work/testng/src.

import org.testng.Assert;
import org.testng.annotations.Test;

public class DependencyTestUsingAnnotation {


String message = "Manisha";
MessageUtil messageUtil = new MessageUtil(message);

@Test(groups = { "init" })
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
message = "Manisha";
Assert.assertEquals(message, messageUtil.printMessage());
}

@Test(dependsOnGroups = { "init.*" })
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Manisha";
Assert.assertEquals(message, messageUtil.salutationMessage());
}

@Test(groups = { "init" })
public void initEnvironmentTest() {
System.out.println("This is initEnvironmentTest");
}
}
In this example, testSalutationMessage() is declared as depending on any group, matching the regular
expression "init.*", which guarantees that the methods testPrintMessage() and initEnvironmentTest() will
always be invoked before testSalutationMessage().
/** If a method depended upon fails, and you have a hard dependency on it (alwaysRun=false,
which is the default), the methods that depend on it are not marked as FAIL but as SKIP. Skipped
methods will be reported as such in the final report (in a color that is neither Red nor Green in
HTML), which is important since skipped methods are not necessarily failures.
Create testng.xml in /work/testng/src to execute test case(s).

<?xml version = "1.0" encoding = "UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name = "Suite1">


<test name = "test1">
<classes>
<class name = "DependencyTestUsingAnnotation" />
</classes>
</test>
</suite>

Verify the output.


This is initEnvironmentTest
Inside testPrintMessage()
Manisha
Inside testSalutationMessage()
Hi!Manisha

===============================================
Suite1
Total tests run: 3, Failures: 0, Skips: 0
===============================================

dependsOnGroups Vs dependsOnMethods
• On using groups, we are no longer exposed to refactoring problems. As long as we don’t modify the
dependsOnGroups or groups attributes, our tests will keep running with the proper dependencies
set up.
• Whenever a new method needs to be added in the dependency graph, all we need to do is put it in
the right group and make sure it depends on the correct group. We don’t need to modify any other
method.
Continue with annotation attributes,

Hierarchy of the TestNG Annotations:

o @BeforeSuite
o @BeforeTest
o @BeforeClass
o @BeforeMethod
o @Test
o @AfterMethod
o @AfterClass
o @AfterTest
o @AfterSuite

Annotation attributes: Common ones:

• description
• timeOut
• priority
• dependsOnMethods
• enabled
• groups

Full list:

1. alwaysRun
2. dataProvider
3. dataProviderClass
4. dependsOnGroups
5. dependsOnMethods
6. description
7. enabled
8. expectedExceptions
9. groups
10. invocationCount
11. timeOut
12. priority
Timeout:

The timeOut is a helper attribute in TestNG that can put an end to the execution of a test method if that
method takes time beyond the timeOut duration. A timeOut time is set in milliseconds, after that the test
method will be marked Failed.

Example
@Test

public void ContactVerify(){

System.out.println("Contact validation is successful”);

@Test(timeOut = 1000)

public void LandingPage(){

System.out.println("Landing page verification is successful”);

@Test

public void LoanContact(){

System.out.println("Loan contact details verification is successful”);

After 1000ms, if LandingPage() execution continues , that test method will be considered as failed. The
rest of the test methods will have no impact.

expectedExceptions

TestNG provides an option of tracing the exception handling of code. You can test whether a code throws
a desired exception or not. Here the expectedExceptions parameter is used along with the @Test
annotation. Now, let's see @Test(expectedExceptions) in action.

TestNG provides functionality to test such exception scenarios by allowing the user to specify the type
of exceptions that are expected to be thrown by a test during execution.

Create Test Case Class


• Create a java test class, say, ExpectedExceptionTest.java in /work/testng/src.
• Add an expected exception ArithmeticException to the testPrintMessage() test case.
Following are the contents of ExpectedExceptionTest.java.

import org.testng.Assert;
import org.testng.annotations.Test;

public class ExpectedExceptionTest {


String message = "Manisha";
MessageUtil messageUtil = new MessageUtil(message);

@Test(expectedExceptions = ArithmeticException.class)
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
messageUtil.printMessage();
}
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Manisha";
Assert.assertEquals(message,messageUtil.salutationMessage());
}
}

Create Test Runner


Create testng.xml in /work/testng/src to execute test case(s).
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name = "Suite1">


<test name = "test1">
<classes>
<class name = "ExpectedExceptionTest" />
</classes>
</test>
</suite>

Verify the output. testPrintMessage() test case will be passed.


Inside testPrintMessage()
Manisha
Inside testSalutationMessage()
Hi!Manisha

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

Testing parameters,

TestNG Parameters are the arguments that we pass to the test methods. There are two ways through
which we can pass the parameters to the test methods:

o TestNG Parameters
o TestNG DataProviders

Suppose we want to set the global variables such url settings, username, password or API Keys,
there are some values which are constant in all the test cases, in such case we use the TestNG
Parameters.

TestNG Parameters are present in the xml file. They can be applied either inside the tag or tag. If we
want to apply the parameters to all the test cases,
then the parameters
are applied inside the tag. If the parameter is specific to a particular folder, then the parameter is applied
within a tag.

Case1: When parameters are same for all cases

Public class Sum


{
@Test
@Parameters({"a","b"})
public void add(int c, int d)
{
int sum=c+d;
System.out.println("Sum of two numbers : "+sum);
}
}
Xml eg:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<parameter name="a" value="5"/>
<parameter name="b" value="3"/>
<test name="Sum">
<classes>
<class name= "com.javatpoint.Sum"/>
</classes>
</test>
</suite> <!-- Suite -->
Second case: When parameters are specific.

Fruits .java

{
@Test
@Parameters("mango")
public void mango(String m)
{
System.out.println("Fruits names are: ");
System.out.println(m);
}
@Test
@Parameters("orange")
public void orange(String o)
{
System.out.println(o);
}
}

Vegetable.java

{
@Test
@Parameters("Cauliflower")
public void c(String m)
{
System.out.println("Vegetable names are :");
System.out.println(m);
}
@Test
@Parameters("Ladyfinger")
public void orange (String l)
{
System.out.println(l);
}
}

Xml:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Fruits">
<parameter name="mango" value="mango"/>
<parameter name="orange" value="orange"/>
<classes>
<class name= "com.javatpoint.Fruits"/>
</classes>
</test>
<test name="Vegetables">
<parameter name="Cauliflower" value="Cauliflower"/>
<parameter name="Ladyfinger" value="Ladyfinger"/>
<classes>
<class name= "com.javatpoint.Vegetable"/>
</classes>
</test>
</suite> <!-- Suite -->

Summary:
If test data is common, then parameter tag comes right after |”Suite tag”

If it’s not common then parameter tag comes after test tag of each test

Passing Parameters with Dataproviders


When 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.), parameters can be passed using
Dataproviders.
A Data Provider is a method annotated with @DataProvider. This annotation has only one string
attribute: its name. 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.
The following examples demonstrate how to use data providers. The first example is about
@DataProvider using Vector, String, or Integer as parameter, and the second example is about
@DataProvider using object as parameter.

Eg:

• Create a java test class, say, ParamTestWithDataProvider1.java in /work/testng/src.


• Define the method primeNumbers(), which is defined as a Data provider using the annotation. This
method returns an array of objects.
• Add the test method testPrimeNumberChecker() to your test class. This method takes an Integer
and Boolean as input parameters. This method validates if the parameter passed is a prime number.
• Add the annotation @Test (dataProvider = "test1") to this method. The attribute dataProvider is
mapped to "test1".

@BeforeMethod
public void initialize() {
primeNumberChecker = new PrimeNumberChecker();
}

@DataProvider(name = "test1")
public static Object[][] primeNumbers() {
return new Object[][] {{2, true}, {6, false}, {19, true}, {22, false}, {23, true}};
}

// This test will run 4 times since we have 5 parameters defined


@Test(dataProvider = "test1")
public void testPrimeNumberChecker(Integer inputNumber, Boolean expectedResult) {
System.out.println(inputNumber + " " + expectedResult);
Assert.assertEquals(expectedResult, primeNumberChecker.validate(inputNumber));
}
}

Create testng.xml
Create a testng.xml /work/testng/src to execute Test case(s).

<?xml version = "1.0" encoding = "UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name = "Suite1">


<test name = "test1">
<classes>
<class name = "ParamTestWithDataProvider1" />
</classes>
</test>
</suite>

https://www.toolsqa.com/testng/testng-dataproviders/

Create Test Case Class


• Create a java test class, say, ParamTestWithDataProvider2.java.
• Define the method primeNumbers(), which is defined as a data provider using annotation. This
method returns an array of object.
• Add the test method testMethod() to your test class. This method takes an object bean as
parameter.
• Add the annotation @Test(dataProvider = "test1") to this method. The attribute dataProvider is
mapped to "test1".
Create a java class file named ParamTestWithDataProvider2.java in /work/testng/src.

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

public class ParamTestWithDataProvider2 {


@DataProvider(name = "test1")
public static Object[][] primeNumbers() {
return new Object[][] { { new Bean("hi I am the bean", 111) } };
}

@Test(dataProvider = "test1")
public void testMethod(Bean myBean) {
System.out.println(myBean.getVal() + " " + myBean.getI());
}
}
Create testng.xml
Create testng.xml in /work/testng/src to execute test case(s).

<?xml version = "1.0" encoding = "UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name = "Suite1">


<test name = "test1">
<classes>
<class name = "ParamTestWithDataProvider2" />
</classes>
</test>
</suite>
Compile the test case class using javac.
/work/testng/src$ javac ParamTestWithDataProvider2.java Bean.java
Now, run testng.xml.
/work/testng/src$ java org.testng.TestNG testng.xml
Verify the output.
hi I am the bean 111

===============================================
Suite1
Total tests run: 1, Failures: 0, Skips: 0
If the tester has not specified the name of the data provider, then the method name becomes the
dataprovider name by default. TestNG dataprovider returns a 2d list of objects. The method then
performs a data-driven test for each value that you have specified

TestNG will automatically try to convert the value specified in testng.xml to the type of your
parameter. Here are the types supported −

• Stringint/Integer
• float/Float
• long/Long
• short/Short
• boolean/Boolean
• byte/Byte
• char/Character
• double/Double

TestNG Listeners

TestNG provides the @Listeners annotation which listens to every event that occurs in a selenium code.
Listeners are activated either before the test or after the test case. It is an interface that modifies the
TestNG behavior. For example, when you are running a test case either through selenium or appium and
suddenly a test case fails. We need a screenshot of the test case that has been failed, to achieve such
scenario, TestNG provides a mechanism, i.e., Listeners. When the test case failure occurs, then it is
redirected to the new block written for the screenshot.

Listeners are implemented by the ITestListener interface. An ITestListener interface has the following
methods:

Methods of testNG listeners:

Types of Listeners in TestNG


There are many types of listeners which allows you to change the TestNG’s behavior.

Below are the few TestNG listeners:

1. IAnnotationTransformer ,
2. IAnnotationTransformer2 ,
3. IConfigurable ,
4. IConfigurationListener ,
5. IExecutionListener,
6. IHookable ,
7. IInvokedMethodListener ,
8. IInvokedMethodListener2 ,
9. IMethodInterceptor ,
10. IReporter,
11. ISuiteListener,
12. ITestListener .

Above Interface are called TestNG Listeners. These interfaces are used in selenium to generate logs or
customize the TestNG reports.

onTestStart(): An onTestStart() is invoked only when any test method gets started.

onTestSuccess(): An onTestSuccess() method is executed on the success of a test method.

onTestFailure(): An onTestFailure() method is invoked when test method fails.

onTestSkipped(): An onTestSkipped() run only when any test method has been skipped.

onTestFailedButWithinSuccessPercentage(): This method is invoked each time when the test method
fails but within success percentage.

onStart(): An onStart() method is executed on the start of any test method.

onFinish(): An onFinish() is invoked when any test case finishes its execution.
How to create the TestNG Listeners

We can create the TestNG Listeners in two ways. First, we can use the @Listeners annotation within the
class and second way to use the within the suite.

First case: First, we will create the listeners within the class.

Step 1: Open the Eclipse.

Step 2: We create a simple project.

import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners(com.javatpoint.Listener.class)
public class Class1
{
@Test
public void sum()
{
int sum=0;
int a=5;
int b=7;
sum=a+b;
System.out.println(sum);
}
@Test
public void testtofail()
{
System.out.println("Test case has been failed");
Assert.assertTrue(false);
}
}

In the above code, we create two test cases, i.e., sum() and testtofail().

Listener.java

package com.javatpoint;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class Listener implements ITestListener
{
@Override
public void onTestStart(ITestResult result) {
// TODO Auto-generated method stub
}

@Override
public void onTestSuccess(ITestResult result) {
// TODO Auto-generated method stub
System.out.println("Success of test cases and its details are : "+result.getName());
}

@Override
public void onTestFailure(ITestResult result) {
// TODO Auto-generated method stub
System.out.println("Failure of test cases and its details are : "+result.getName());
}

@Override
public void onTestSkipped(ITestResult result) {
// TODO Auto-generated method stub
System.out.println("Skip of test cases and its details are : "+result.getName());
}

@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
// TODO Auto-generated method stub
System.out.println("Failure of test cases and its details are : "+result.getName());
}

@Override
public void onStart(ITestContext context) {
// TODO Auto-generated method stub
}

@Override
public void onFinish(ITestContext context) {
// TODO Auto-generated method stub
}
}
When sum() test case has been passed, then TestNG calls the onTestSuccess() listener. When
testtofail() test case has been failed, then TestNG calls the onTestFailure() listener.

Step 3: Now, we create the testng.xml file.

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Listeners">
<classes>
<class name="com.javatpoint.Class1"></class>
</classes>
</test>
</suite> <!-- Suite -->

Step 4: Run the testng.xml file. Right click on the testng.xml file and move the cursor down to Run
As and then click on the 1 TestNG Suite.

2nd case of creating the listener:

Second case: Now we create the listeners by using testng.xml file.


Step 1: Open the Eclipse.

Step 2: We will create two java projects. One java project is containing the test cases and another project
is containing listeners.

Testcases.java

package com.javatpoint;
import org.testng.Assert;
import org.testng.annotations.Test;
public class Testcases
{
@Test
public void testtopass()
{
Assert.assertTrue(true);
}
@Test
public void testtofail()
{
Assert.assertFalse(false);
}
}

Listener.java

package com.javatpoint;

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

public class Listener implements ITestListener


{

@Override
public void onTestStart(ITestResult result) {
// TODO Auto-generated method stub

@Override
public void onTestSuccess(ITestResult result) {
// TODO Auto-generated method stub
System.out.println("Success of test cases and its details are : "+result.getName());
}

@Override
public void onTestFailure(ITestResult result) {
// TODO Auto-generated method stub
System.out.println("Failure of test cases and its details are : "+result.getName());
}

@Override
public void onTestSkipped(ITestResult result) {
// TODO Auto-generated method stub
System.out.println("Skip of test cases and its details are : "+result.getName());
}

@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
// TODO Auto-generated method stub
System.out.println("Failure of test cases and its details are : "+result.getName());
}

@Override
public void onStart(ITestContext context) {
// TODO Auto-generated method stub

@Override
public void onFinish(ITestContext context) {
// TODO Auto-generated method stub

}
}

Step 3: Now, we create the testng.xml file.

testng.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<listeners>
<listener class-name="com.javatpoint.Listener"/>
</listeners>
<test name="Listeners_program">
<classes>
<class name="com.javatpoint.Testcases"></class>
</classes>
</test>
</suite>
<!-- Suite -->

Step 4: Run the testng.xml file.

Output

Note: When listeners are added to multiple classes then it could be an error prone. If listeners are
implemented through the testng.xml file, then they are applied to all the classes.

Summary,

Listener can be implemented using both through class file and through the xml file

• onStart: This method invokes when the test class is instantiated and before executing any test
method.

• onTestStart: This method invokes every time a test method is called and executed.
TestNG Reports

What are TestNG Reports?

TestNG Reports are the default HTML reports which are generated once the test cases are executed
using TestNG. These reports help you to identify the information about test cases and the status of a
project. TestNG reports in Selenium have three methods passTest, failTest, and skipTest to check the
data about test cases.

Report generation is very important when you are doing the Automation Testing as well as for Manual
Testing.

By looking at the result, you can easily identify how many test cases are passed, failed and skipped.

By looking at the report, you will come to know what the status of the project is.

Selenium web driver is used for automating the web-application, but it won’t generate any reports.

The TestNG will generate the default report.

When you execute testng.xml file, and refresh the project. You will get test-output folder in that folder for
reporting in TestNG.

Right click on the emailable-report.html and select the option. Open with the web browser.

In this tutorial, you will learn-

Method-1: emailable-report.html

Method-2: index.html

Method-3: Reporter Class

How to generate reports in Selenium


Method-1: emailable-report.html
1. Click on option “emailable-report.html”
2. Click on option web browser
The output reports in TestNG reporting will look like below if both the
classes are passed:
Consider the scenario in where you are intentionally failing the test case
i.e. DemoB class. Then convert both the classes into testng.xml suite file
and run it. Then the result will look like this. It will show the failed test
cases.

This is result for DemoB class:


Similarly, result for the Class DemoA will look like this:

Method-2 index.html
1. Right click on the index.html from the project directory.
2. Select option open with web browser option. It will display the result
in the following order.

The result will look like this:


Method-3 Reporter Class
Along with these TestNG report generated methods, you can use
object.properties file to store the system generated logs as well as user
generated logs. But one of the simplest ways to store log information in
testing is using Reporter Class.

Reporter.log in Selenium is a class present in TestNG for Selenium


reporting. It provides 4 different methods to store log information they are:

1. Reporter.log(String s);
2. Reporter.log(String s, Boolean logToStandardOut);
3. Reporter.log(String s, int level);
4. Reporter.log(String s, int level, Boolean logToStandardOut);

Example:

Create Two classes such as DemoA and DemoB and write the following
code inside the classes.

For Class DemoA;

• The Code for DemoA is already explained above. Here you are
using log method of Reporter class. (For implementing a reporting
class, the class has to implement an org.testng.IReporter interface).
• The log method is a static method of Reporter class. So you are
accessing that method through the Reporter class.
• The log method is used to store log information that is written inside
the program. By looking at the log information, you will easily come
to know where exactly the execution of the program is stopped.
For Class DemoB:

• Now, Create testng.xml file by selecting these two classes and


• Select run as and
• Click on the convert to testng.
• Then run this testng.xml file by selecting run as and select testng
suite.
• Then refresh the project open the test-output folder.
1. In the test-output folder, open the emailable-report.html. It will look
like:

Similarly, you will have an Output for Demo B project as well.

2. In test-output folder open the index.html. It will look like:


Click on reporter output. It will open logging info whatever written in the
test methods.

Click on the Times. It will going to show how much time it took to run the
test method present in class using TestNG reporting tools.
Video player testing:

https://medium.com/@sudharsanselvaraj.c/automating-the-testing-of-video-players-by-using-selenium-
and-tesseract-ocr-ecb6cb4a7ac3

22-11-2022
https://www.guru99.com/scroll-up-down-selenium-webdriver.html
Scroll in Selenium:
To scroll using Selenium, you can use JavaScriptExecutor interface that helps to execute JavaScript
methods through Selenium Webdriver

js.executeScript("window.scrollBy(0,1000)"); //Scroll vertically down by 1000 pixels

js.executeScript("arguments[0].scrollIntoView();",Element );

Scenario 3: To scroll down the web page at the bottom of the page.

js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

Scenario 4: Horizontal scroll on the web page.

js.executeScript("arguments[0].scrollIntoView();",Element );

Syntax:

JavascriptExecutor js = (JavascriptExecutor) driver;


js.executeScript(Script,Arguments);

• Script – This is the JavaScript that needs to execute.


• Arguments – It is the arguments to the script. It’s optional.

Scenario 1: To scroll down the web page by pixel.


Selenium Script

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

public class ScrollByPixel {

WebDriver driver;
@Test
public void ByPixel() {
System.setProperty("webdriver.chrome.driver", "E://Selenium//Selenium_Jars//chromedriver.exe");
driver = new ChromeDriver();

JavascriptExecutor js = (JavascriptExecutor) driver;


// Launch the application
driver.get("http://demo.guru99.com/test/guru99home/");

//To maximize the window. This code may not work with Selenium 3 jars. If script fails you can
remove the line below
driver.manage().window().maximize();

// This will scroll down the page by 1000 pixel vertical


js.executeScript("window.scrollBy(0,1000)");
}
}
Script Description: In the above code first we launch the given URL in Chrome browser. Next, scroll the
page by 1000 pixels through executeScript. Javascript method ScrollBy() scrolls the web page to the
specific number of pixels.

The syntax of ScrollBy() methods is :

executeScript("window.scrollBy(x-pixels,y-pixels)");
x-pixels is the number at x-axis, it moves to the left if number is positive and it move to the right if number
is negative .y-pixels is the number at y-axis, it moves to the down if number is positive and it move to the
up if number is in negative .

Example:
js.executeScript("window.scrollBy(0,1000)"); //Scroll vertically down by 1000 pixels
Output analysis : Here is the output when you execute the above script .
Scenario 2: To scroll down the web page by the visibility of the element.
Selenium Script

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.testng.annotations.Test;

public class ScrollByVisibleElement {

WebDriver driver;
@Test
public void ByVisibleElement() {
System.setProperty("webdriver.chrome.driver", "G://chromedriver.exe");
driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;

//Launch the application


driver.get("http://demo.guru99.com/test/guru99home/");

//Find element by link text and store in variable "Element"


WebElement Element = driver.findElement(By.linkText("Linux"));

//This will scroll the page till the element is found


js.executeScript("arguments[0].scrollIntoView();", Element);
}
}
Script Description: In the above code, we first launch the given url in Chrome browser. Next, scroll the
page until the mentioned element is visible on the current page. Javascript method scrollIntoView() scrolls
the page until the mentioned element is in full view:

js.executeScript("arguments[0].scrollIntoView();",Element );
“arguments[0]” means first index of page starting at 0.

Where an” Element” is the locator on the web page.

Output analysis: Here is the output when you execute the above script .
Scenario 3: To scroll down the web page at the bottom of the page.
public class ScrollByPage {

WebDriver driver;
@Test
public void ByPage() {
System.setProperty("webdriver.chrome.driver", "E://Selenium//Selenium_Jars//chromedriver.exe");
driver = new ChromeDriver();

JavascriptExecutor js = (JavascriptExecutor) driver;

// Launch the application


driver.get("http://demo.guru99.com/test/guru99home/");

//This will scroll the web page till end.


js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
}
}
Script Description : In the above code, we first launch the given url in Chrome browser. Next, scroll till
the bottom of the page. Javascript method scrollTo() scroll the till the end of the page .

js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
“document.body.scrollHeight” returns the complete height of the body i.e web page.

Output analysis: Here is the output when you execute the above script.
Scenario 4: Horizontal scroll on the web page.
Selenium Script

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.testng.annotations.Test;

public class HorizontalScroll {

WebDriver driver;
@Test
public void ScrollHorizontally() {
System.setProperty("webdriver.chrome.driver", "E://Selenium//Selenium_Jars//chromedriver.exe");
driver = new ChromeDriver();

JavascriptExecutor js = (JavascriptExecutor) driver;

// Launch the application


driver.get("http://demo.guru99.com/test/guru99home/scrolling.html");

WebElement Element = driver.findElement(By.linkText("VBScript"));

//This will scroll the page Horizontally till the element is found
js.executeScript("arguments[0].scrollIntoView();", Element);
}
}
Script Description : In the above code, we first launch the given url in Chrome browser. Next, scroll the
page horizontally until the mentioned element is visible on the current page. Javascript method
scrollIntoView() scrolls the page until the mentioned element is in full view :

js.executeScript("arguments[0].scrollIntoView();",Element );
Output analysis: Here is the output when you execute the above script.
How do you Scroll to the top of the page in Selenium?

js.executeScript("window.scrollTo(document.body.scrollHeight,0)");

summary:

https://testsigma.com/blog/scrolling-in-selenium/#For_Horizontal_Scroll

scroll to bottom:

js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

//*(x,y) = x horizontal, y=vertical

scrollto top:

js.executeScript("window.scrollTo(document.body.scrollHeight,0)");

Scroll horizontally and vertically:

js.executeScript("arguments[0].scrollIntoView();", Element);

Syntax

window.scrollBy(x, y)

or just:

scrollBy(x, y)

Parameters

Parameter Description

x Required.
Number of pixels to scroll (horizontally).
Positive values scroll to the right, negative values to the left.
y Required.
Number ofpixels to scroll (vertically).
Positive values scroll down, negative values scroll up.

scroll to an element:
js.executeScript("arguments[0].scrollIntoView();",Element );

Input text without sendkeys:

How to input text in the text box without calling the sendKeys() using Selenium?
SeleniumAutomation TestingTesting Tools

We can input text in the text box without the method sendKeys with the help of the JavaScript Executor.
Selenium executes JavaScript commands with the help of the executeScript method.
The JavaScript command to be run is passed as parameter to the method. To enter text we shall first
identify the input box with the JavaScript method document.getElementById. Then we have to apply the
value method on it.
Let us enter text Selenium in the below input box −

Syntax
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript ("document.getElementById('gsc-i-id1').value='Selenium'");

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class JsEnterText{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.tutorialspoint.com/index.htm");
// JavaScript Executor to enter text
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript ("document.getElementById('gsc-i-id1').value='Selenium'");
WebElement l = driver.findElement(By.id("gsc-i-id1"));
String s = l.getAttribute("value");
System.out.println("Value entered is: " + s);
driver.quit();
}
}

Different alternates of sending keys in selenium:

(1) Using Robot Class

This will program will open notepad and write QUORA in it

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

public class sendKeysUsingBot{

public static void main(String[] args) throws AWTException,IOException {

Runtime.getRuntime().exec("notepad");

Robot robot = new Robot();

robot.keyPress(KeyEvent.VK_Q);
robot.keyRelease(KeyEvent.VK_Q);

robot.keyPress(KeyEvent.VK_U);
robot.keyRelease(KeyEvent.VK_U);

robot.keyPress(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_O);

robot.keyPress(KeyEvent.VK_R);
robot.keyRelease(KeyEvent.VK_R);

robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
}
}
(2) Using Javascript Script Executor

WebDriver driver = new ChromeDriver();


driver.get("http://www.facebook.com");
WebElement username = driver.findElement(By.id("username"));
JavascriptExecutor runJS= ((JavascriptExecutor) driver);
runJS.executeScript("arguments[0].value='admin';", username);
driver.quit();
(3) Using Action class

WebDriver driver = new ChromeDriver();


driver.get("http://www.facebook.com");
WebElement username = driver.findElement(By.id("username"));
Actions performAct = new Actions(driver);
performAct.sendKeys(username, "admin").build().perform();

JS for the use case of without using click():

Alternative of click () in Selenium

There are several alternatives to the usage of click method in Selenium webdriver. We can use the
JavaScript Executor to perform a click action. Selenium can execute JavaScript commands with the help
of the executeScript method.
The parameters – arguments[0].click() and locator of the element on which the click is to be performed
are passed to this method.

Syntax
WebElement n=driver.findElement(By.linkText("Refund"));
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].click();", n);

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class JsClickLink{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//launch URL
driver.get("https://www.tutorialspoint.com/index.htm");
// identify element
WebElement m = driver.findElement(By.xpath("//a[@title='TutorialsPoint - Home']"));
// click with Javascript Executor
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].click();", m);
driver.quit();
}
}
If we want to click the submit button within a form tag having the value of type attribute as submit, it can
be done using the submit method.
Let us the html code of a button with type=submit within the form tag.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class ClsNameStrategy{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.linkedin.com/");
// identify element
WebElement l = driver.findElement(By.className("input__input"));
l.sendKeys("[email protected]");
WebElement x = driver.findElement(By.id("session_password"));

x.sendKeys("1258147");
WebElement m = driver.
findElement(By.cssSelector("button[type='submit']"));
//click button with type submit
m.submit();
driver.close();
}
}

What is the difference between an Alert and a Popup?

Alert and a popup are graphical user interface components used to show the user information in a

different window or dialog box.

Alerts Pop-ups

A message box in the middle of the screen is A pop-up is a small window that overlays the active
an alert. screen.

They are utilized to provide users with crucial Pop-ups are frequently used to ask for more details or to
information or alerts. confirm a decision.

They are frequently used to show error


They are often used to request further information or to
messages or other crucial information, like
display advertisements and are typically smaller and less
verifying a decision that can have
repercussions. intrusive than warnings.

Popups can have more complex layouts and functions.


Alerts have a simple design with a brief
For instance, a pop-up can have a form for the user to fill
message and one or more buttons that the
out, a video player to watch, or a calendar to choose a
user can press to respond.
date.

https://www.w3schools.com/js/js_popup.asp#:~:text=A%20prompt%20box%20is%20often,Cancel%22%2
0the%20box%20returns%20null

Handling dropdown/ Using Select Class in selenium:

Select Class in Selenium

The Select Class in Selenium is a method used to implement the HTML SELECT tag. The html select
tag provides helper methods to select and deselect the elements. The Select class is an ordinary class so
New keyword is used to create its object and it specifies the web element location.

Select Option from Drop-Down Box


Following is a step by step process on how to select value from dropdown in Selenium:

Before handling dropdown in Selenium and controlling drop-down boxes, we must do following two
things:

1. Import the package org.openqa.selenium.support.ui.Select


2. Instantiate the drop-down box as an object, Select in Selenium WebDriver

As an example, go to Mercury Tours’ Registration page


(http://demo.guru99.com/test/newtours/register.php) and notice the “Country” drop-down box there.
Step 1

Import the “Select” package.

Step 2

Declare the drop-down element as an instance of the Select class. In the example below, we named this
instance as “drpCountry”.

Step 3

We can now start controlling “drpCountry” by using any of the available Select methods to select
dropdown in Selenium. The sample code below will select the option “ANTARCTICA.”

Selecting Items in a Multiple SELECT elements


We can also use the selectByVisibleText() method in selecting multiple options in a multi SELECT
element. As an example, we will take https://jsbin.com/osebed/2 as the base URL. It contains a drop-
down box that allows multiple selections at a time.
The code below will select the first two options using the selectByVisibleText() method.

Here is the complete code


package newpackage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.By;

public class accessDropDown {


public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
String baseURL = "http://demo.guru99.com/test/newtours/register.php";
WebDriver driver = new FirefoxDriver();
driver.get(baseURL);

Select drpCountry = new Select(driver.findElement(By.name("country")));


drpCountry.selectByVisibleText("ANTARCTICA");
//Selecting Items in a Multiple SELECT elements
driver.get("http://jsbin.com/osebed/2");
Select fruits = new Select(driver.findElement(By.id("fruits")));
fruits.selectByVisibleText("Banana");
fruits.selectByIndex(1);
}
}

Summary:

Element Command Description

selectByVisibleText()/
selects/deselects an option by its displayed text
deselectByVisibleText()
selectByValue()/ selects/deselects an option by the value of its “value”
attribute
deselectByValue()
Drop-Down Box selectByIndex()/
selects/deselects an option by its index
deselectByIndex()
returns TRUE if the drop-down element allows
isMultiple()
multiple selection at a time; FALSE if otherwise

deselectAll() deselects all previously selected options

To control drop-down boxes, you must first import the org.openqa.selenium.support.ui.Select package
and then create a Select instance.

Select all options:

-check if its multi select

-get the length/count of options

-loop through each options and select them using normalmethod.


CSS Selector:

What is a CSS Selector?


CSS Selectors in Selenium are string patterns used to identify an element based on a combination of
HTML tag, id, class, and attributes. Locating by CSS Selectors in Selenium is more complicated than the
previous methods, but it is the most common locating strategy of advanced Selenium users because it
can access even those elements that have no ID or name.

CSS Selectors in Selenium have many formats, but we will only focus on the most common ones. The
different types of CSS Locator in Selenium IDE

• Tag and ID
• Tag and class
• Tag and attribute
• Tag, class, and attribute
• Inner text
Tag and ID:

Syntax

css=tag#id

• tag = the HTML tag of the element being accessed


• # = the hash sign. This should always be present when using a Selenium CSS Selector with ID
• id = the ID of the element being accessed

tag and class – CSS Selector


CSS Selector in Selenium using an HTML tag and a class name is similar to using a tag and ID, but in
this case, a dot (.) is used instead of a hash sign.

Syntax

css=tag.class

• tag = the HTML tag of the element being accessed


• . = the dot sign. This should always be present when using a CSS Selector with class
• class = the class of the element being accessed
Take note that when multiple elements have the same HTML tag and name, only the first element
in source code will be recognized. Using Firebug, inspect the Password text box in Facebook and
notice that it has the same name as the Email or Phone text box.Tag and attribute – CSS Selector

This strategy uses the HTML tag and a specific attribute of the element to be accessed.

Syntax

css=tag[attribute=value]

• tag = the HTML tag of the element being accessed


• [ and ] = square brackets within which a specific attribute and its corresponding value will be
placed
• attribute = the attribute to be used. It is advisable to use an attribute that is unique to the element
such as a name or ID.
• value = the corresponding value of the chosen attribute.
tag, class, and attribute – CSS Selector
Syntax

css=tag.class[attribute=value]

• tag = the HTML tag of the element being accessed


• . = the dot sign. This should always be present when using a CSS Selector with class
• class = the class of the element being accessed
• [ and ] = square brackets within which a specific attribute and its corresponding value will be
placed
• attribute = the attribute to be used. It is advisable to use an attribute that is unique to the element
such as a name or ID.
• value = the corresponding value of the chosen attribute.
inner text – CSS Selector
As you may have noticed, HTML labels are seldom given id, name, or class attributes. So, how do we
access them? The answer is through the use of their inner texts. Inner texts are the actual string
patterns that the HTML label shows on the page.

Syntax

css=tag:contains("inner text")

• tag = the HTML tag of the element being accessed


• inner text = the inner text of the element
Tag: contains ("inner text")

Summary

Syntax for Locating by CSS Selector Usage

Method Target Syntax Example


Tag and ID css=tag#id css=input#email
Tag and Class css=tag.class css=input.inputtext
Tag and Attribute css=tag[attribute=value] css=input[name=lastName]
Tag, Class, and Attribute css=tag.class[attribute=value] css=input.inputtext[tabindex=1]

Files uploading in Selenium can be done with the below methods:

1. Using sendKeys method


2. Using AutoIT tool
3. With the help of Robot Class

Using sendKeys method”

Uploading Files
For this section, we will use http://demo.guru99.com/test/upload/ as our test application. This site easily
allows any visitor to upload files without requiring them to sign up.

Uploading files in WebDriver is done by simply using the sendKeys() method on the file-select
input field to enter the path to the file to be uploaded.
Handle File upload popup in Selenium Webdriver

Handle file upload popup in selenium Webdriver

Let’s say we wish to upload the file “C:\newhtml.html”. Our WebDriver code should be like the one shown
below.

package newproject;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PG9 {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
String baseUrl = "http://demo.guru99.com/test/upload/";
WebDriver driver = new FirefoxDriver();

driver.get(baseUrl);
WebElement uploadElement = driver.findElement(By.id("uploadfile_0"));

// enter the file path onto the file-selection input field


uploadElement.sendKeys("C:\\newhtml.html");

// check the "I accept the terms of service" check box


driver.findElement(By.id("terms")).click();

// click the "UploadFile" button


driver.findElement(By.name("send")).click();
}
}
After running this script, you should be able to upload the file successfully and you should get a message
similar to this.

Remember following two things when uploading files in WebDriver

1. There is no need to simulate the clicking of the “Browse” button. WebDriver automatically enters
the file path onto the file-selection text box of the <input type=”file”> element
2. When setting the file path in your Java IDE, use the proper escape character for the back-slash.
Robot class:

Robots as we know help in managing various activities such as performing some tasks, handling the
keyboard functions, the mouse functions, and many more. Here we will understand certain functions that
are helpful in controlling the keyboard and the mouse while an application is being tested using Selenium.
Key Events or Methods for implementing the Robot Class
In the implementation of Robot class, there are a few methods for the execution of test scripts.

https://www.toolsqa.com/selenium-webdriver/robot-class/

These are mentioned below:


• KeyPress(): This method is called when we want to press any key.
• Example: robot.keyPress(KeyEvent.VK_ENTER);
• KeyRelease(): This method is used to release the pressed key.
• Example: robot.keyRelease(KeyEvent.VK_ENTER);
• MouseMove(): Used when there is a need of moving the mouse pointer over ‘X’ and ‘Y’
coordinates.
• Example: robot.mouseMove(coordinates.get.X(), coordinates.get.Y());
• MousePress(): This method is called when we want to press the left mouse button.
• Example: robot.mousePress(InputEvent.BUTTON_MASK);
• MouseRelease(): This method is used to release the pressed mouse button.
• Example: robot.mouseRelease(InputEvent.BUTTON_DOWN_MASK);

Robot Class Mouse Events


Let us understand some of the essential techniques of the Robot class, which are
used to simulate the mouse events.

• mousePress(int buttons): This method presses one or more mouse buttons.

Here, parameter buttons are the Button mask. Which, in turn, is a combination of one or more mouse
button masks.

Following are standard button masks available for mousePress method :

• InputEvent.BUTTON1_DOWN_MASK : For mouse left -click


• InputEvent.BUTTON2_DOWN_MASK : For mouse middle button click.
• InputEvent.BUTTON3_DOWN_MASK : For mouse right-click
• InputEvent.BUTTON1_MASK
• InputEvent.BUTTON2_MASK
• InputEvent.BUTTON3_MASK
• mouseRelease(int buttons): This method releases one or more mouse buttons. For Example,
robot.mouseRelease(InputEvent. BUTTON1_DOWN_MASK) will release the left click press of
the mouse.
• mouseMove(int x, int y): This method moves the mouse pointer to the given screen position.
Here, x is X position, and y is Y position in the coordinates. For Example, the method
mouseMove(100, 50) will move the mouse pointer to the x coordinate 100 and y coordinate 50 on
the screen.
Advantages of Robot Class
• File upload using the robot class is easy.
• It handles the keyboard and mouse functions.
• Handling pop-ups is also possible.
Disadvantages of Robot Class
• Keyboard or mouse event would work only on the current instance of the window.
• While executing a robot event, if the code execution is moved to another window, the mouse or
keyboard event still remains on the previous window.
• It is not easy to switch among different windows.

Implementation of code for File Upload using Robot Class:

For this, we will consider the example of the Grammarly.com website. Below is the implementation code
for handling file upload in Selenium using Robot class.
package SeleniumPrograms;

import java.awt.AWTException;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.util.concurrent.TimeUnit;
import java.awt.Robot;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.sun.glass.events.KeyEvent;

public class FileUpload_Robo {

public static void main(String[] args) throws InterruptedException, AWTException {


// TODO Auto-generated method stub

WebDriver drv = new FirefoxDriver(); // starting Firefox browser


drv.manage().window().maximize(); // maximizing window
drv.manage().timeouts().pageLoadTimeout(10, TimeUnit. SECONDS);//for page load
drv.get("https://www.grammarly.com/plagiarism-checker");//open testing website
drv.manage().timeouts().implicitlyWait(10, TimeUnit. SECONDS);// for Implicit wait

JavascriptExecutor js = (JavascriptExecutor)drv; // Scroll operation using Js Executor


js.executeScript("window.scrollBy(0,200)"); // Scroll Down(+ve) upto browse option
Thread.sleep(2000); // suspending execution for specified time period

WebElement browse = drv.findElement(By.linkText("Upload a file"));


// using linkText, to click on browse element
browse.click(); // Click on browse option on the webpage
Thread.sleep(2000); // suspending execution for specified time period

// creating object of Robot class


Robot rb = new Robot();
// copying File path to Clipboard
StringSelection str = new StringSelection("C:\\Users\\Chait\\Desktop\\File upload.docx");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(str, null);

// press Contol+V for pasting


rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);

// release Contol+V for pasting


rb.keyRelease(KeyEvent.VK_CONTROL);
rb.keyRelease(KeyEvent.VK_V);

// for pressing and releasing Enter


rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
}

}
The output for the above selenium code is shown below:

Thus, files can be uploaded with the help of a robot class, where we can see the use of input events like
Key Pressing and Key Releasing for copying, pasting, entering, etc.
Robot class methods:

Actions Class:

Actions class is a collection of individual Action that you want to perform. For e.g. we may want to
perform a mouse click on an element. In this case we are looking at two different Action

1. Moving the mouse pointer to the element


2. Clicking on the element

Individual action mentioned above are represented by a class called Action, we will talk about it later.
Collection of such Action is represented by the Actions class.

There is a huge collection of methods available in Actions class. The below screenshot shows the list of
methods available.
Also, an important thing to bring here is that there is one another class which is called Action Class and
it is different from Actions class. Because maybe you have noticed the top blue line in the above
screenshot, the build method returns Action class.

What is the difference between Actions Class and Action Class in Selenium?

With the above explanations of Actions Class & Action Class, we can now conclude that Actions is a
class that is based on a builder design pattern. This is a user-facing API for emulating complex user
gestures.

Whereas Action is an Interface which represents a single user-interaction action. It contains one of the
most widely used methods perform ().

Example1:

/Hover

/moveto

In the following example, we shall use the moveToElement() method to mouse-over on one Mercury
Tours’ table rows. See the example below.
The cell shown above is a portion of a <TR> element. If not hovered, its color is #FFC455 (orange). After
hovering, the cell’s color becomes transparent. It becomes the same color as the blue background of the
whole orange table.

Step 1: Import the Actions and Action classes.

Step 2: Instantiate a new Actions object.

Step 3: Instantiate an Action using the Actions object in step 2.

In this case, we are going to use the moveToElement() method because we are simply going to mouse-
over the “Home” link. The build() method is always the final method used so that all the listed actions will
be compiled into a single step.

Step 4: Use the perform() method when executing the Action object we designed in Step 3.

Below is the whole WebDriver code to check the background color of the <TR> element before and after
the mouse-over.

package newproject;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class PG7 {

public static void main(String[] args) {


String baseUrl = "http://demo.guru99.com/test/newtours/";
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();

driver.get(baseUrl);
WebElement link_Home = driver.findElement(By.linkText("Home"));
WebElement td_Home = driver
.findElement(By
.xpath("//html/body/div"
+ "/table/tbody/tr/td"
+ "/table/tbody/tr/td"
+ "/table/tbody/tr/td"
+ "/table/tbody/tr"));

Actions builder = new Actions(driver);


Action mouseOverHome = builder
.moveToElement(link_Home)
.build();

String bgColor = td_Home.getCssValue("background-color");


System.out.println("Before hover: " + bgColor);
mouseOverHome.perform();
bgColor = td_Home.getCssValue("background-color");
System.out.println("After hover: " + bgColor);
driver.close();
}
}

The output below clearly states that the background color became transparent after the mouse-over.

Building a Series of Multiple Actions


You can build a series of actions using the Action and Actions classes. Just remember to close the
series with the build() method. Consider the sample code below.
Public static void main(String[] args) {
String baseUrl = "http://www.facebook.com/";
WebDriver driver = new FirefoxDriver();

driver.get(baseUrl);
WebElement txtUsername = driver.findElement(By.id("email"));

Actions builder = new Actions(driver);


Action seriesOfActions = builder
.moveToElement(txtUsername)
.click()
.keyDown(txtUsername, Keys.SHIFT)
.sendKeys(txtUsername, "hello")
.keyUp(txtUsername, Keys.SHIFT)
.doubleClick(txtUsername)
.contextClick()
.build();

seriesOfActions.perform() ;

}
Summary

• Handling special keyboard and mouse events are done using the AdvancedUserInteractions API.
• Frequently used Keyword and Mouse Events are doubleClick(), keyUp, dragAndDropBy,
contextClick & sendKeys.

Syntax for drag and drop.


The Actions class has two methods that support Drag and Drop. Let’s study them-

Actions.dragAndDrop(Sourcelocator, Destinationlocator)
In dragAndDrop method, we pass the two parameters –

1. First parameter “Sourcelocator” is the element which we need to drag


2. Second parameter “Destinationlocator” is the element on which we need to drop the first element

Actions.dragAndDropBy(Sourcelocator, x-axis pixel of Destinationlocator, y-axis pixel of


Destinationlocator)
dragAndDropBy method we pass the 3 parameters –

1. First parameter “Sourcelocator” is the element which we need to drag


2. The second parameter is x-axis pixel value of the 2nd element on which we need to drop the first
element.
3. The third parameter is y-axis pixel value of the 2nd element on which we need to drop the first
element.

Let’s practically show you the drag and drop of an element using the selenium webdriver with following 3
scenarios

• Scenario 1: BANK element is dragged and dropped on the specific element by DragAndDrop
method.
• Scenario 2: BANK element is dragged and dropped on the specific element by DragAndDrop
method.
• Scenario 3: Few elements are dragged and dropped and then verify the message is displayed or
not.

Scenario 1: BANK element is dragged and dropped on the specific cell by DragAndDrop method.
In the following code, we launch the given URL in Firefox browser and then drag the BANK element and
drop on the DEBIT SIDE block through dragAndDrop method.

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.testng.annotations.Test;

public class DragAndDrop {

WebDriver driver;

@Test
public void DragnDrop()
{
System.setProperty("webdriver.chrome.driver"," E://Selenium//Selenium_Jars//chromedriver.exe ");
driver= new ChromeDriver();
driver.get("http://demo.guru99.com/test/drag_drop.html");

//Element which needs to drag.


WebElement From=driver.findElement(By.xpath("//*[@id='credit2']/a"));

//Element on which need to drop.


WebElement To=driver.findElement(By.xpath("//*[@id='bank']/li"));

//Using Action class for drag and drop.


Actions act=new Actions(driver);

//Dragged and dropped.


act.dragAndDrop(From, To).build().perform();
}
}

Scenario 2: BANK element is dragged and dropped on the specific cell by DragAndDrop method.
In this scenario, we launch the given URL in the browser and then drag the BANK element and drop on
the DEBIT SIDE block through dragAndDropBy method. To dragAndDropBy, we need to find the pixel of
the element.

How to find Pixel?

Open the URL in Chrome or FireFox and click on the Blue color arrow.

Next click on any element for which you want to know the pixel.

You will find the pixel above the element as shown in below screenshot.

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.testng.annotations.Test;

public class DragAndDrop {

WebDriver driver;
@Test
public void DragnDrop()
{
System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//chromedriver.exe");
driver= new ChromeDriver();
driver.get("http://demo.guru99.com/test/drag_drop.html");
//Element(BANK) which need to drag.
WebElement From=driver.findElement(By.xpath("//*[@id='credit2']/a"));

//Using Action class for drag and drop.


Actions act=new Actions(driver);

//Drag and Drop by Offset.


act.dragAndDropBy(From,135, 40).build().perform();
}
}

NOTE: The pixels values change with screen resolution and browser size. This method is hence not
reliable and not widely used.

Scenario 3: Few elements are dragged and dropped and then verify the message is displayed or
not.
In the following code, we launch the given URL in the browser and then drag the elements like BANK,
SALES, 500 and drop on the respective block. Once done we verify the output message.

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.testng.annotations.Test;

public class DragAndDrop {

WebDriver driver;
@Test
public void DragnDrop()
{
System.setProperty("webdriver.chrome.driver","
E://Selenium//Selenium_Jars//chromedriver.exe");
driver= new ChromeDriver();
driver.get("http://demo.guru99.com/test/drag_drop.html");

//Element(BANK) which need to drag.


WebElement From1=driver.findElement(By.xpath("//*[@id='credit2']/a"));

//Element(DEBIT SIDE) on which need to drop.


WebElement To1=driver.findElement(By.xpath("//*[@id='bank']/li"));

//Element(SALES) which need to drag.


WebElement From2=driver.findElement(By.xpath("//*[@id='credit1']/a"));

//Element(CREDIT SIDE) on which need to drop.


WebElement To2=driver.findElement(By.xpath("//*[@id='loan']/li"));

//Element(500) which need to drag.


WebElement From3=driver.findElement(By.xpath("//*[@id='fourth']/a"));
//Element(DEBIT SIDE) on which need to drop.
WebElement To3=driver.findElement(By.xpath("//*[@id='amt7']/li"));

//Element(500) which need to drag.


WebElement From4=driver.findElement(By.xpath("//*[@id='fourth']/a"));

//Element(CREDIT SIDE) on which need to drop.


WebElement To4=driver.findElement(By.xpath("//*[@id='amt8']/li"));

//Using Action class for drag and drop.


Actions act=new Actions(driver);

//BANK drag and drop.


act.dragAndDrop(From1, To1).build().perform();

//SALES drag and drop.


act.dragAndDrop(From2, To2).build().perform();

//500 drag and drop debit side.


act.dragAndDrop(From3, To3).build().perform();

//500 drag and drop credit side.


act.dragAndDrop(From4, To4).build().perform();

//Verifying the Perfect! message.


if(driver.findElement(By.xpath("//a[contains(text(),'Perfect')]")).isDisplayed())
{
System.out.println("Perfect Displayed !!!");
}
else
{
System.out.println("Perfect not Displayed !!!");
}
}
Output analysis

In Output, you can see the element is dragged and dropped on the defined element. You can check the
GIF of the output.

Summary

• In the above tutorials, we illustrate the drag and drop functionality of the web application through
Action methods in Webdriver:
• dragAndDrop(Sourcelocator, Destinationlocator)
• dragAndDropBy(Sourcelocator, x-axis pixel of Destinationlocator, y-axis pixel of
Destinationlocator)
• To drag and drop the element first we used DragAndDrop method from the Actions class in which
we pass the 2 parameters, 1st parameter is the element which we need to drag, and
2nd parameter is the element on which we need to drop the 1st element.
• Second, we used the dragAndDropBy method from the Actions class in which we pass the 3
parameters, the 1st parameter is the element which we need to drag, 2nd parameter is the x-axis
pixel value of the 2nd element, 3rd parameter is the y-axis pixel value of the 2nd element.
• Actions vs Robot The Main Difference is Actions class simulates with mouse and keyboard and
Robot class enables the actual mouse and keyboard so you can see the movement of the mouse
cursor. For more Details please Click on this Link -> Robot class in Selenium
How to Perform Click and Hold in Selenium WebDriver

Click and hold is an action in Selenium in which we do left-click on an element and hold it without
releasing the left button of the mouse.

To perform this action in Selenium WebDriver, we will use clickAndHold() method of actions class.
This method is generally useful in executing drag and drop operations.
So, let’s take a scenario where we will click and hold at the current location action. Follow all the steps to
complete the below scenario.
Scenario to Automate:
1. Launch the Firefox browser.
2. Open the URL “https://selenium08.blogspot.com/2020/01/click-and-hold.html”.
3. Locate the element by By.xpath.
4. Move the cursor to the position of title C.
5. Click and hold title C.
6. Move the cursor to any position.

Let’s create a test case where we will automate the following scenario.

Program source code 1:


package clickAndHoldAction;
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.interactions.Actions;

public class ClickAndHold


{
public static void main(String[] args)
{
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();

String url = "https://selenium08.blogspot.com/2020/01/click-and-hold.html";


driver.get(url);

// Locate the element C by By.xpath.


WebElement titleC = driver.findElement(By.xpath("//li[text()= 'C']"));

// Create an object of actions class and pass reference of WebDriver as a parameter to its constructor.
Actions actions = new Actions(driver);

// Move the cursor to the position of element C.


actions.moveToElement(titleC); // Call clickAndHold() method to perform click and hold operation.
actions.clickAndHold().perform();
}
}
The title movement will be similar to the below screenshot as shown below.

In this example program, first, we move cursor to the location of title C and then click and hold title C.
When we will move the cursor to the location of title B then title B has been shifted to location of title
C.You can also move title C anywhere. Now execute this in your eclipse and see what happens.

How to Perform Click and Hold WebElement Action in Selenium WebDriver

In the previous section, we have seen clickAndHold() method of actions class which will click and hold a
WebElement at current position of the cursor. But this method does not deal with a particular web
element.
So, if you want to deal with a particular WebElement on a web page, you will have to use an overloaded
version of clickAndHold() method of actions class. It helps to avoid moving of cursor to location of any
web element.
The API syntax of an overloaded version of clickAndHold method is as follows:
public Actions clickAndHold(WebElement onElement)

This method accepts a WebElement as an input parameter that has to be clicked and held.
Let’s modify coding in the previous example to use overloaded version of clickAndHold() method.
Program source code 2:
package clickAndHoldAction;
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.interactions.Actions;

public class ClickAndHold


{
public static void main(String[] args)
{
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();

String url = "https://selenium08.blogspot.com/2020/01/click-and-hold.html";


driver.get(url);

// Locate the element C by By.xpath.


WebElement titleC = driver.findElement(By.xpath("//li[text()= 'C']"));

// Create an object of actions class and pass reference of WebDriver as a parameter to its constructor.
Actions actions = new Actions(driver);

// Call clickAndHold() method to perform click and hold operation on element C.


actions.clickAndHold(titleC).perform();
}
}
The only change in this coding is that we have removed the action of moving cursor and provided
WebElement to clickAndHold() method that will take care of identifying of WebElement.

Hope that this tutorial has covered almost all important points related to click and hold in Selenium
WebDriver. I hope that you will have understood this topic and performed the scenario in your eclipse

Taking Screenshot:

Screenshot in Selenium Web driver


A Screenshot in Selenium Web driver is used for bug analysis. Selenium web driver can automatically
take screenshots during the execution. But if users need to capture a screenshot on their own, they need
to use the Take Screenshot method which notifies the Web Drive to take the screenshot and store it in
Selenium.

In this tutorial, you will learn,

• Capture Screenshot using Selenium WebDriver


• What is Ashot API?
• How to download and configure Ashot API?
• Capture Full Page Screenshot with AShot API
• Taking a screenshot of a particular element of the page
• Image Comparison using AShot

Capture Screenshot using Selenium WebDriver

Taking Screenshot in Selenium is a 3 Step process

Step 1) Convert web driver object to TakeScreenshot

TakesScreenshot scrShot =((TakesScreenshot)webdriver);

Step 2) Call getScreenshotAs method to create image file


File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);

Step 3) Copy file to Desired Location

Example: In this example we will take screen capture of http://demo.guru99.com/V4/ & save it as
C:/Test.png

package Guru99TakeScreenshot;

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 Guru99TakeScreenshot {

@Test

public void testGuru99TakeScreenShot() throws Exception{

WebDriver driver ;
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
driver = new FirefoxDriver();

//goto url

driver.get("http://demo.guru99.com/V4/");

//Call take screenshot function

this.takeSnapShot(driver, "c://test.png") ;

/**

* This function will take screenshot

* @param webdriver

* @param fileWithPath

* @throws Exception

*/
public static void takeSnapShot(WebDriver webdriver,String fileWithPath) throws Exception{

//Convert web driver object to TakeScreenshot

TakesScreenshot scrShot =((TakesScreenshot)webdriver);

//Call getScreenshotAs method to create image file

File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);

//Move image file to new destination

File DestFile=new File(fileWithPath);

//Copy file at destination

FileUtils.copyFile(SrcFile, DestFile);

NOTE: Selenium version 3.9.0 and above does not provide Apache Commons IO JAR. You can simply
download them here and call them in your project

What is Ashot API?

Ashot is a third party utility by Yandex supported by Selenium WebDriver to capture the Screenshots. It
takes a screenshot of an individual WebElement as well as a full-page screenshot of a page, which is
more significant than screen size.

To configure through Maven:

Go to https://mvnrepository.com/artifact/ru.yandex.qatools.ashot/ashot

Click on the latest version, for now. It is 1.5.4

Copy the Dependency code and add to your pom.xml file

Save the file, and Maven will add the jar to your build path

And now you are ready!!!


Capture Full Page Screenshot with AShot API
Step 1) Create an Ashot object and call takeScreenshot() method if you just want the screenshot for the
screen size page.

Screenshot screenshot = new Ashot().takeScreenshot(driver);


But if you want a screenshot of the page bigger then the screen size, call the shootingStrategy() method
before calling takeScreenshot() method to set up the policy. Then call a method takeScreenshot() passing
the webdriver, for example,

Screenshot screenshot = new


AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
Here 1000 is scrolled out time in milliseconds, so for taking a screenshot, the program will scroll for each
1000 msec.

Step 2): Now, get the image from the screenshot and write it to the file. You can provide the file type as
jpg, png, etc.

ImageIO.write(screenshot.getImage(), "jpg", new File(".\\screenshot\\fullimage.jpg"));


Taking a full-page screenshot of a page which is bigger than screen size.

Example: Here is the example of capturing a full-page screenshot


of https://demo.guru99.com/test/guru99home/ and save to file “screenshot.jpg.”

Due to using the ShootingStrategy class of Ashot API, we will be able to capture a full image of a page
bigger than the screen size.

Here is the screenshot code in selenium program:

package Guru99;

import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;

public class TestScreenshotUsingAshot {

public static void main(String[] args) throws IOException {

System.setProperty("webdriver.chrome.driver", "c:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();

driver.get("https://demo.guru99.com/test/guru99home/");
driver.manage().window().maximize();
Screenshot = new
AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreen
shot(driver);

ImageIO.write(screenshot.getImage(), "jpg", new


File("c:\\ElementScreenshot.jpg"));

Image Comparison using AShot


package Guru99;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.comparison.ImageDiff;
import ru.yandex.qatools.ashot.comparison.ImageDiffer;

public class TestImageComaprison {

public static void main(String[] args) throws IOException {

System.setProperty("webdriver.chrome.driver",
"C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.guru99.com/test/guru99home/");

// Find the element and take a screenshot

WebElement logoElement = driver.findElement(By.xpath("//*[@id=\"site-


name\"]/a[1]/img"));
Screenshot logoElementScreenshot = new AShot().takeScreenshot(driver,
logoElemnent);

// read the image to compare

BufferedImage expectedImage = ImageIO.read(new


File("C:\\Guru99logo.png"));

BufferedImage actualImage = logoElementScreenshot.getImage();

// Create ImageDiffer object and call method makeDiff()

ImageDiffer imgDiff = new ImageDiffer();


ImageDiff diff = imgDiff.makeDiff(actualImage, expectedImage);

if (diff.hasDiff() == true) {
System.out.println("Images are same");

} else {
System.out.println("Images are different");
}
driver.quit();
}
}
Summary

• Ashot API is a freeware from Yandex.


• It is a utility for taking a screenshot in Selenium.
• It helps you to take a screenshot of an individual WebElement on different platforms like desktop
browsers, iOS Simulator Mobile Safari, Android Emulator Browser.
• It can take a page screenshot of a page bigger than screen size.
• This feature has been removed in selenium version 3, so Ashot API is a good option.
• It can decorate the screenshots.
• It provides a screenshot comparison.

Chrome Options & Desired Capabilities in Selenium Webdriver

What is Chrome Options Class?


The Chromeoptions Class is a concept in Selenium WebDriver for manipulating various properties of
the Chrome driver. The Chrome options class is generally used in conjunction with Desired Capabilities
for customizing Chrome driver sessions. It helps you perform various operations like opening Chrome in
maximized mode, disable existing extensions, disable pop-ups, etc.
Example:

Below example shows a way to open Chrome browser in maximized mode using ChromeOptions class.
We need to pass an instance of ChromeOptions class to the web driver initialization.

ChromeOptions options = new ChromeOptions()


options.addArgument("start-maximized");
ChromeDriver driver = new ChromeDriver(options);
Below are the list of available and most commonly used arguments for ChromeOptions class

• start-maximized: Opens Chrome in maximize mode


• incognito: Opens Chrome in incognito mode
• headless: Opens Chrome in headless mode
• disable-extensions: Disables existing extensions on Chrome browser
• disable-popup-blocking: Disables pop-ups displayed on Chrome browser
• make-default-browser: Makes Chrome default browser
• version: Prints chrome browser version
• disable-infobars: Prevents Chrome from displaying the notification ‘Chrome is being controlled
by automated software

*****Disable info bars, Updated Code:

options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));

options.setExperimentalOption("useAutomationExtension", false);

Desired Capabilities class

Desired Capabilities Class is used to modify multiple properties of web drivers. It provides key-value
pairs to change individual properties of web drivers such as browser name, browser platform, etc. A
common method of Desired Capabilities class is the setCapability method. It is mostly used with Selenium
Grid, where the same test case needs to be executed on different browsers.
Example:

Below example shows the way to enable chrome browser to accept SSL certificates on websites
by default using Desired Capabilities for Chrome class.
// Create an object of desired capabilities class with Chrome driver
DesiredCapabilities SSLCertificate = DesiredCapabilities.chrome();
// Set the pre-defined capability – ACCEPT_SSL_CERTS value to true
SSLCertificate.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
// Open a new instance of chrome driver with the desired capability
WebDriver driver = new ChromeDriver(SSLCertificate);
Below are the most commonly used pre-defined capability types.

Capability Name Description

ACCEPT_SSL_CERTS This property tells the browser to accept SSL Certificates by default

This property is used to set the operating system platform used to access the web
PLATFORM_NAME
site

BROWSER_NAME This property is used to set the browser name for a web driver instance

VERSION This property to used to set the browser version

Chrome Options for Incognito mode


Chrome Options can be used for incognito mode by using the pre-defined argument –incognito.

Below is the sample code to accomplish the same.

Sample Code:

package test;
import java.io.File;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

public class Incognito{


public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver","X://chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
options.merge(capabilities);
ChromeDriver driver = new ChromeDriver(options);
driver.get("http://demo.guru99.com/test/simple_context_menu.html");
driver.manage().window().maximize();
//driver.quit();
}
}
Code Explanation:

1. Initially, you need to set the path to the chromedriver.exe file using set property method since you
are using Chrome Browser for testing
2. Then you need to create an object of Chrome Options class and pass it to web driver instance.
Since we want to open Chrome browser in incognito mode, you need to pass the argument –
incognito to Chrome Options class.
3. Next, create an object of Desired Capabilities class and merge the Desired Capabilities class
object with Chrome Options class object using merge method
4. You need to create an object of Chrome Driver class and pass the Chrome Options object as an
argument
5. Finally, we need to pass the URL – http://demo.guru99.com/test/simple_context_menu.html to the
driver.get method
6. Maximize and close the browser

Output:

The chrome browser window will be opened in Incognito mode as below

Chrome Options for Headless Chrome


A Headless browser runs in the background. You will not see the browser GUI or the operations been
operated on it.

Chrome Options for running Chrome browser in headless mode can be accomplished by using the
predefined arguments –headless.

Sample code to accomplish it is mentioned below.

Example:

package test;
import java.io.File;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
public class HeadlessModeDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver","X://chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
options.merge(capabilities);
ChromeDriver driver = new ChromeDriver(options);
driver.get("http://demo.guru99.com/");
driver.manage().window().maximize();
String title = driver.getTitle();
System.out.println("Page Title: " +title);
driver.quit();
}

}
Code Explanation:

1. Initially, you need to set the path to the chromedriver.exe file using set property method since you
are using Chrome Browser for testing
2. Next, create an object of Chrome Options class and pass it to web driver instance. Since we want
to open Chrome browser in headless mode, we need to pass the argument –headless to Chrome
Options class.
3. Create an object of DesiredCapabilities Chrome class and merge the Desired Capabilities class
object with Chrome Options class object using merge method
4. Create an object of Chrome Driver class and pass the Chrome Options Selenium object as an
argument
5. Finally, we need to pass the URL – http://demo.guru99.com/ to the driver.get method
6. Print the page title and close the browser

Output

The browser will not be visible for the above code as Chrome will be working in Headless mode. Page
title will be fetched and displayed as below.
Testing extensions in chrome:

Here’s the syntax for this code in a number of languages often used in Selenium Webdriver scripts:

-download crx extractor download extension from chrome and then follow the below code

-download any extension you want and install

-right click and download the crx file for the installed extension

Java:

ChromeOptions options = new ChromeOptions ();

options.addExtensions (new File("/path/to/extension.crx"));


DesiredCapabilities capabilities = new DesiredCapabilities ();

capabilities.setCapability(ChromeOptions.CAPABILITY, options);

ChromeDriver driver = new ChromeDriver(capabilities);

Summary:

• Selenium Chrome Options class is used to manipulate various properties of Chrome driver
• Desired Chrome Capabilities class provides a set of key-value pairs to modify individual
properties of web driver such as browser name, browser platform, etc.
• To manipulate any extensions of Chrome browser, CRX File corresponding to the extension must
be extracted and must be added to Chrome Options class
• –incognito and –headless are predefined arguments provided by Chrome Options class for using
Chrome browser in incognito mode and headless mode

Maximize and minimize window:

- We can minimize and maximize using normal options available in selenium browser
commands.

https://www.guru99.com/maximize-resize-minimize-browser-selenium.html

System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//ch
romedriver.exe");
driver= new ChromeDriver();

// Launch the application


driver.get("https://www.guru99.com/");

Dimension d = new Dimension(300,1080);


//Resize current window to the set dimension
driver.manage().window().setSize(d);

Handling Windows in selenium:

Handling Multiple Windows in Selenium


Windows are new tabs popups opened within browser

What is a window handle?


It is a unique identifier that holds the address of all the windows. Think of it as a pointer to a window,
which returns the string value. It is assumed that each browser will have a unique window handle. This
window handle function helps to retrieve the handles of all windows.
Getwindowhandle() return type is string
Getwindowhandles() return type is set<string>/Iterator<String>

Syntax

1. get.windowhandle(): This method helps to get the window handle of the current window
2. get.windowhandles(): This method helps to get the handles of all the windows opened
3. set: This method helps to set the window handles in the form of a string. set<string> set=
driver.get.windowhandles()
4. switch to: This method helps to switch between the windows
5. action: This method helps to perform certain actions on the windows
These are some of the methods that will be used to handle multiple windows in Selenium.

People also read: How to handle Alerts and Popups in Selenium?

Example of handling multiple windows


Scenario: Navigate to the Browserstack home page. This is the parent window. From the parent window,
let’s see how to handle the child windows and then again navigate back to the parent windows.
Steps to execute:

1. Get the handle of the parent window using the command:

String parentWindowHandle = driver.getWindowHandle();

2. Print the window handle of the parent window.


3. Find the element on the web page using an ID which is an element locator.
4. Open multiple child windows.
5. Iterate through child windows.
6. Get the handles of all the windows that are currently open using the command: Set<String>
allWindowHandles = driver.getWindowHandles(); which returns the set of handles.
7. Use the SwitchTo command to switch to the desired window and also pass the URL of the web
page.
Refer to the complete program below.
Before running the code, one should do a quick check on 6 things to avoid while running selenium
scrips. Check it out.
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class WindowHandle_Demo {


public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver","Path to the driver");
WebDriver driver = new ChromeDriver();

driver.manage().window().maximize();

// Load the website


driver.get("http://www.naukri.com/");

// It will return the parent window name as a String


String parent=driver.getWindowHandle();

Set<String>s=driver.getWindowHandles();

// Now iterate using Iterator


Iterator<String> I1= s.iterator();

while(I1.hasNext())
{

String child_window=I1.next();
if(!parent.equals(child_window))
{
driver.switchTo().window(child_window);

System.out.println(driver.switchTo().window(child_window).getTitle());

driver.close();
}

}
//switch to the parent window
driver.switchTo().window(parent);
}
}

Output:

On executing the parent window handle, it will open multiple child windows and then navigate back to the
final window handle.

Now let’s perform some actions on the Browserstack website.

• Use the javascriptexecutor to scroll down through a page.


• Find the element using XPath and send keys (which is of the form string) to that particular element
location.
• Declare the web element Link to click on a particular link on the page. In this case, the link must open in a
new window.
• Get the window handles of all the windows and print them in a sequential manner.
• Switch to the parent window and check if the title matches. If it does, scroll down the page using
the javascriptexecutor.
• Find another element on the web page using the element locator and specify the position of the new
window.
• Switch back to the parent window and scroll down through the page.

Code Snippet
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class selenium { public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.browserstack.com/");
String title = driver.getTitle(); System.out.println(title);

JavascriptExecutor js = (JavascriptExecutor) driver;


driver.findElement(By.xpath("//span[contains(text(),'Solutions')]")).click();
driver.findElement(By.xpath("//a[contains(text(),'Geolocation Testing')]")).click();
js.executeScript("window.scrollBy(0,40)");

WebElement link = driver.findElement(By.xpath("//a[@id='product-menu-toggle']//span[@class='account-


down-caret']//*[local-name()='svg']"));
Actions newwin = new Actions(driver);
newwin.keyDown(Keys.SHIFT).click(link).keyUp(Keys.SHIFT).build().perform();
//Thread.sleep(2000);
//js.executeScript("window.scrollBy(0,400)");
Thread.sleep(3000);
Set<String> windows = driver.getWindowHandles();
System.out.println(windows);
System.out.println("a1");
for (String window : windows)
{
driver.switchTo().window(window);
if (driver.getTitle().contains("Most Reliable App & Cross Browser Testing Platform | Browserstack"))
{
System.out.println("a2");
js.executeScript("window.scrollBy(0,1000)");
System.out.println("b1");
driver.findElement(By.xpath("//a[@id='logo']//*[local-name()='svg']")).click();

driver.findElement(By.xpath("//a[@id='signupModalButton']")).click();
driver.manage().window().setPosition(new Point(2000, 0));
}
}
Thread.sleep(3000);
Set<String> windows1 = driver.getWindowHandles();
System.out.println(windows1);
System.out.println("a3");
for (String window : windows1)
{
driver.switchTo().window(window);
System.out.println("a4");
js.executeScript("window.scrollBy(0,400)");
}
}
}

On executing the code above, it will launch multiple windows and the window handle will be retrieved.
Run the code, automate user navigation through multiple windows, and ensure the website works
perfectly in real user conditions. With Selenium WebDriver, ensure that websites offer an optimal user
experience in all possible circumstances.

Handling Frames:

Frame is an html document that is included in another html document

Used to place the contents of another source especially advertisement,images, videos..etc

A website can have multiple frames in a single page.

Identifying frames:

Frames can be identified by right clicking on them and selecting the option ”This frame”,or inspect and
use //iframe

Handling Frames:

• We need to switch to a particular frame to handle it


• Switch methods are designed for switching to frames, alerts, and windows.
• Once steps are completed, we need to switch back to parent/main frame.
SwitchToMethods():

Method name Description


Switchto().frame(int index) Switches to a frame by its index
Switchto().frame(String framename) Switches to a frame by the frame name
Switchto().frame(WebElement element) Switches to a frame by the web element
identifier passed
Switchto().defaultContent() Switches to the first frame or main document
Switchto().parentFrame() Changes focus to parent frame

Alerts:
The simplest of these is referred to as an alert, which shows a custom message, and a single button
which dismisses the alert, labelled in most browsers as OK. It can also be dismissed in most browsers by
pressing the close button, but this will always do the same thing as the OK button. See an example alert.

WebDriver can get the text from the popup and accept or dismiss these alerts.

//Click the link to activate the alert


driver.findElement(By.linkText("See an example alert")).click();

//Wait for the alert to be displayed and store it in a variable


Alert alert = wait.until(ExpectedConditions.alertIsPresent());

//Store the alert text in a variable


String text = alert.getText();

//Press the OK button


alert.accept();

Copy

Confirm
A confirm box is similar to an alert, except the user can also choose to cancel the message. See a
sample confirm.

This example also shows a different approach to storing an alert:

//Click the link to activate the alert


driver.findElement(By.linkText("See a sample confirm")).click();

//Wait for the alert to be displayed


wait.until(ExpectedConditions.alertIsPresent());

//Store the alert in a variable


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

//Store the alert in a variable for reuse


String text = alert.getText();

//Press the Cancel button


alert.dismiss();

Copy

Prompt
Prompts are similar to confirm boxes, except they also include a text input. Similar to working with form
elements, you can use WebDriver’s send keys to fill in a response. This will completely replace the
placeholder text. Pressing the cancel button will not submit any text. See a sample prompt.

//Click the link to activate the alert


driver.findElement(By.linkText("See a sample ")).click();

//Wait for the alert to be displayed and store it in a variable


Alert alert = wait.until(ExpectedConditions.alertIsPresent());

//Type your message


alert.sendKeys("Selenium");

//Press the OK button


alert.accept();

Alert methods:

Accept() Void()
Dismiss() Void()
GetText() Return type string
SendKeys() Void()

Modal Popup:

https://automatenow.io/how-to-work-with-modals-in-
selenium/#:~:text=Modal%20vs%20alert%20boxes%20or,user%20must%20switch%20to%20it.&tex
t=Switching%20is%20not%20necessary%20for%20modals%2C%20as%20you%20will%20see%20n
ext.

A modal is a popup window displayed on top of the current page, and there are different types of modals.
Some can be very simple, as in the following example.
As you can see, this modal only displays a message and a button that a user can click on to close the
modal.

You may need to fill out a form in other modals

Notice that this modal not only contains a button to close the modal but that it also contains a form.

It is important to note that all modals require immediate attention. That means that a user must either
interact with the modal or dismiss. Otherwise, they won’t be able to return to the main web page.

Modal vs alert boxes or windows

The main difference between a modal and an alert box is that modals do not require unique methods to
work with them. For example, before interacting with an alert box, a user must switch to it.

driver.switchTo().alert()

Switching is not necessary for modals, as you will see next.

How to work with modals in Selenium

To enter text in a modal window you first locate the input element, then you simply enter the text. This
code snippet shows you how to do this.

Modal: enter text

driver.findElement(locator).clear();

driver.findElement(locator).sendKeys(text);

What is Ajax?
AJAX stands for Asynchronous JavaScript & XML, and it allows the Web page to retrieve small
amounts of data from the server without reloading the entire page.

Ajax is a technique used for creating fast and dynamic web pages. This technique is asynchronous and
uses a combination of Javascript and XML .

It will updates the part/s of a web page without reloading the whole page.

Some of the famous applications that uses AJAX technique are Gmail, Google Maps, Facebook,
Youtube, etc.

In this tutorial, you will learn-

• What is Ajax?
• How Ajax Works?
• How to handle Ajax call Using Selenium Webdriver
• Challenges in Handling Ajax Call in Selenium Webdriver
How Ajax Works?
For example, when you click on submit button, JavaScript will make a request to the server, interpret the
result and update the current screen without reloading the webpage.

• An Ajax call is an asynchronous request initiated by the browser that does not directly result in a
page transition. It means, if you fire an Ajax request, the user can still work on the application
while the request is waiting for a response.
• AJAX sends HTTP requests from the client to server and then process the server’s response,
without reloading the entire page. So, when you make an AJAX call, you are not pretty sure
about the time taken by the server to send you a response.

From a tester’s point of view, if you are checking the content or the element to be displayed , you need to
wait till you get the response. During AJAX call the data is stored in XML format and retrieved from the
server.

How to handle Ajax call Using Selenium Webdriver


The biggest challenge in handling Ajax call is knowing the loading time for the web page. Since the
loading of the web page will last only for a fraction of seconds, it is difficult for the tester to test such
application through automation tool. For that, Selenium Webdriver has to use the wait method on this
Ajax Call.

So by executing this wait command, selenium will suspend the execution of current Test Case and wait
for the expected or new value. When the new value or field appears, the suspended test cases will get
executed by Selenium Webdriver.

Following are the wait methods that Selenium Webdriver can use

1. Thread.Sleep()
• Thread.Sleep () is not a wise choice as it suspends the current thread for the specified amount of
time.
• In AJAX, you can never be sure about the exact wait time. So, your test will fail if the element
won’t show up within the wait time. Moreover, it increases the overhead because calling
Thread.sleep(t) makes the current thread to be moved from the running queue to the
waiting queue.
• After the time ‘t’ reached, the current thread will move from the waiting queue to the ready
queue, and then it takes some time to be picked by the CPU and be running.

2. Implicit Wait()

• This method tells webdriver to wait if the element is not available immediately, but this wait will be
in place for the entire time the browser is open. So any search for the elements on the page could
take the time the implicit wait is set for.

3. Explicit Wait()

• Explicit wait is used to freeze the test execution till the time a particular condition is met or
maximum time lapses.

4. WebdriverWait

• It can be used for any conditions. This can be achieved with WebDriverWait in combination with
ExpectedCondition
• The best way to wait for an element dynamically is checking for the condition every second and
continuing to the next command in the script as soon as the condition is met.

But the problem with all these waits is, you have to mention the time out unit. What if the element is still
not present within the time? So there is one more wait called Fluent wait.

5. Fluent Wait

• This is an implementation of the Wait interface having its timeout and polling interval. Each
FluentWait instance determines the maximum amount of time to wait for a condition, as well as
the frequency with which to check the condition.

Challenges in Handling Ajax Call in Selenium Webdriver

• Using “pause” command for handling Ajax call is not completely reliable. Long pause time makes
the test unacceptably slow and increases the Testing time. Instead, “waitforcondition” will be
more helpful in testing Ajax applications.
• It is difficult to assess the risk associated with particular Ajax applications
• Given full freedom to developers to modify Ajax application makes the testing process
challenging
• Creating automated test request may be difficult for testing tools as such AJAX application often
use different encoding or serialization technique to submit POST data.

An Example for Ajax HANDLING


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.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Ajaxdemo {

private String URL = "http://demo.guru99.com/test/ajax.html";

WebDriver driver;
WebDriverWait wait;

@BeforeClass
public void setUp() {
System.setProperty("webdriver.chrome.driver",".\\chromedriver.exe");
//create chrome instance
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to(URL);
}

@Test
public void test_AjaxExample() {

By container = By.cssSelector(".container");
wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(container));

//Get the text before performing an ajax call


WebElement noTextElement = driver.findElement(By.className("radiobutton"));
String textBefore = noTextElement.getText().trim();

//Click on the radio button


driver.findElement(By.id("yes")).click();

//Click on Check Button


driver.findElement(By.id("buttoncheck")).click();

/*Get the text after ajax call*/


WebElement TextElement = driver.findElement(By.className("radiobutton"));
wait.until(ExpectedConditions.visibilityOf(TextElement));
String textAfter = TextElement.getText().trim();

/*Verify both texts before ajax call and after ajax call text.*/
Assert.assertNotEquals(textBefore, textAfter);
System.out.println("Ajax Call Performed");

String expectedText = "Radio button is checked and it's value is Yes";

/*Verify expected text with text updated after ajax call*/


Assert.assertEquals(textAfter, expectedText);
driver.close();
}

Summary:

• AJAX allows the Web page to retrieve small amounts of data from the server without reloading
the entire page.
• To test Ajax application, different wait methods should be applied
• ThreadSleep
• Implicit Wait
• Explicit Wait
• WebdriverWait
• Fluent Wait
• Creating automated test request may be difficult for testing tools as such AJAX application often
use different encoding or serialization technique to submit POST data.

Set the position of browser window:

https://seleniumatfingertips.wordpress.com/tag/setposition/

How To Set Browser Window Position In Selenium Webdriver

Today, we are going to discuss how to set browser window position in selenium webdriver. Window
position means distance of window from left side(X Coordinates) of screen and top side(Y Coordinates)
of screen. To set the browser window position, we are using setPosition() method of selenium webdriver.
Code snippet to set browser window position using selenium webdriver :
Specify the X and Y coordinate details in setPosition method.

//WebDriver used to set window position x coordinate = 100 and y coordinate = 200.
driver.manage().window().setPosition(new Point(100,200));

Code snippet to get the X and Y of browser window position using selenium webdriver :
This will help you to get the X and Y coordinate position of browser window.
//WebDriver used to get window position x,y coordinates.
System.out.println("Window position X coordinates Is -> "+driver.manage().window().getPosition().getX());
System.out.println("Window position Y coordinates Is -> "+driver.manage().window().getPosition().getY());

Set the browser window position in selenium webdriver:


Let’s see the example of webdriver script, which will help you to set the browser window position during
the time of script execution.

SeleniumDemo.java

package demoPackage;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumDemo {

public static WebDriver driver;

public static void main(String[] args) {


// TODO Auto-generated method stub

System.out.println("Launching the chrome driver ");

// Set the chrome driver exe file path

System.setProperty("webdriver.chrome.driver","E:\\selenium_sumit\\chromedriver_win32_2.33\\chromedri
ver.exe");

// Instantiate the chrome driver


driver = new ChromeDriver();

// set the browser URL in get() to load the webpage


driver.get("https://google.com/");

//WebDriver used to set window position x coordinate = 100 and y coordinate = 200.
driver.manage().window().setPosition(new Point(100,200));

//WebDriver used to get window position x,y coordinates.


System.out.println("Window position X coordinates Is ->
"+driver.manage().window().getPosition().getX());
System.out.println("Window position Y coordinates Is ->
"+driver.manage().window().getPosition().getY());

This is all about setting the browser window position in selenium during the run time. Thank you for
reading this article, and if you have any problem, have a another better useful solution about this article,
please write message in the comment section.

Setting up size of browser:

If you run your scripts in headless mode or on the cloud then maximizing the window browser does not
work sometimes and you may get NoSuchElementException. In this case, setting the browser window
size explicitly will work.

To test the responsiveness of your application with different sizes of browser windows also requires
setting the size of the browser window explicitly.
Theory:

Topics on automation testing

https://www.guru99.com/automation-testing.html
What is Automation Testing?
Automation Testing is a software testing technique that performs using special automated testing
software tools to execute a test case suite. On the contrary, Manual Testing is performed by a human
sitting in front of a computer carefully executing the test steps.
The automation testing software can also enter test data into the System Under Test, compare expected
and actual results and generate detailed test reports. Software Test Automation demands considerable
investments of money and resources.

Successive development cycles will require execution of same test suite repeatedly. Using a test
automation tool, it’s possible to record this test suite and re-play it as required. Once the test suite is
automated, no human intervention is required. This improved ROI of Test Automation. The goal of
Automation is to reduce the number of test cases to be run manually and not to eliminate Manual
Testing altogether.

Click here if the video is not accessible

In this automated software testing tutorial, you will learn:

• What is Automation Testing?


• Why Test Automation?
• Which Test Cases to Automate?
• Automated Testing Process:
• Test tool selection
• Define the scope of Automation
• Planning, Design, and Development
• Test Execution
• Test Automation Maintenance Approach
• Framework for Automation
• Automation Tool Best Practices
• Benefits of Automation Testing
• Types of Automated Testing
• How to Choose an Automation Tool?
• Automation Testing Tools
Why Test Automation?

Why Test Automation?

Test Automation is the best way to increase the effectiveness, test coverage, and execution speed in
software testing. Automated software testing is important due to the following reasons:

• Manual Testing of all workflows, all fields, all negative scenarios is time and money consuming
• It is difficult to test for multilingual sites manually
• Test Automation in software testing does not require Human intervention. You can run automated
test unattended (overnight)
• Test Automation increases the speed of test execution
• Automation helps increase Test Coverage
• Manual Testing can become boring and hence error-prone.

Which Test Cases to Automate?


Test cases to be automated can be selected using the following criterion to increase the automation ROI

• High Risk – Business Critical test cases


• Test cases that are repeatedly executed
• Test Cases that are very tedious or difficult to perform manually
• Test Cases which are time-consuming

The following category of test cases are not suitable for automation:

• Test Cases that are newly designed and not executed manually at least once
• Test Cases for which the requirements are frequently changing
• Test cases which are executed on an ad-hoc basis.

Automated Testing Process:


Following steps are followed in an Automation Process

Step 1) Test Tool Selection

Step 2) Define scope of Automation


Step 3) Planning, Design and Development

Step 4) Test Execution

Step 5) Maintenance

Test Automation Process

Test tool selection


Test Tool selection largely depends on the technology the Application Under Test is built on. For
instance, QTP does not support Informatica. So QTP cannot be used for
testing Informatica applications. It’s a good idea to conduct a Proof of Concept of Tool on AUT.

Define the scope of Automation


The scope of automation is the area of your Application Under Test which will be automated. Following
points help determine scope:

• The features that are important for the business


• Scenarios which have a large amount of data
• Common functionalities across applications
• Technical feasibility
• The extent to which business components are reused
• The complexity of test cases
• Ability to use the same test cases for cross-browser testing

Planning, Design, and Development


During this phase, you create an Automation strategy & plan, which contains the following details-

• Automation tools selected


• Framework design and its features
• In-Scope and Out-of-scope items of automation
• Automation testbed preparation
• Schedule and Timeline of scripting and execution
• Deliverables of Automation Testing

Test Execution
Automation Scripts are executed during this phase. The scripts need input test data before there are set
to run. Once executed they provide detailed test reports.

Execution can be performed using the automation tool directly or through the Test Management tool
which will invoke the automation tool.

Example: Quality center is the Test Management tool which in turn it will invoke QTP for execution of
automation scripts. Scripts can be executed in a single machine or a group of machines. The execution
can be done during the night, to save time.

Test Automation Maintenance Approach


Test Automation Maintenance Approach is an automation testing phase carried out to test whether the
new functionalities added to the software are working fine or not. Maintenance in automation testing is
executed when new automation scripts are added and need to be reviewed and maintained in order to
improve the effectiveness of automation scripts with each successive release cycle.

Framework for Automation


A framework is set of automation guidelines which help in

• Maintaining consistency of Testing


• Improves test structuring
• Minimum usage of code
• Less Maintenance of code
• Improve re-usability
• Non-Technical testers can be involved in code
• The training period of using the tool can be reduced
• Involves Data wherever appropriate

There are four types of frameworks used in automation software testing:

1. Data Driven Automation Framework


2. Keyword Driven Automation Framework
3. Modular Automation Framework
4. Hybrid Automation Framework

Automation Tool Best Practices


To get maximum ROI of automation, observe the following

• The scope of Automation needs to be determined in detail before the start of the project. This
sets expectations from Automation right.
• Select the right automation tool: A tool must not be selected based on its popularity, but it’s fit to
the automation requirements.
• Choose an appropriate framework
• Scripting Standards- Standards have to be followed while writing the scripts for
Automation. Some of them are-
• Create uniform scripts, comments, and indentation of the code
• Adequate Exception handling – How error is handled on system failure or unexpected behavior of
the application.
• User-defined messages should be coded or standardized for Error Logging for testers to
understand.
• Measure metrics- Success of automation cannot be determined by comparing the manual effort
with the automation effort but by also capturing the following metrics.
• Percent of defects found
• The time required for automation testing for each and every release cycle
• Minimal Time is taken for release
• Customer Satisfaction Index
• Productivity improvement

The above guidelines if observed can greatly help in making your automation successful.

Benefits of Automation Testing

Benefits of Automation Testing

Following are the Test Automation benefits:

• 70% faster than the manual testing


• Wider test coverage of application features
• Reliable in results
• Ensure Consistency
• Saves Time and Cost
• Improves accuracy
• Human Intervention is not required while execution
• Increases Efficiency
• Better speed in executing tests
• Re-usable test scripts
• Test Frequently and thoroughly
• More cycle of execution can be achieved through automation
• Early time to market

Types of Automated Testing

• Smoke Testing
• Unit Testing
• Integration Testing
• Functional Testing
• Keyword Testing
• Regression Testing
• Data Driven Testing
• Black Box Testing

How to Choose an Automation Tool?


Selecting the right tool can be a tricky task. Following criterion will help you select the best tool for your
requirement-

• Environment Support
• Ease of use
• Testing of Database
• Object identification
• Image Testing
• Error Recovery Testing
• Object Mapping
• Scripting Language Used
• Support for various types of test – including functional, test management, mobile, etc…
• Support for multiple testing frameworks
• Easy to debug the automation software scripts
• Ability to recognize objects in any environment
• Extensive test reports and results
• Minimize training cost of selected tools

Tool selection is one of biggest challenges to be tackled before going for automation. First, Identify the
requirements, explore various tools and its capabilities, set the expectation from the tool and go for a
Proof Of Concept.
Waits in Selenium:

Thread.sleep() - It will sleep time for script, not good way to use in script as it's sleep without condition.

- If you use Thread.sleep while performing Selenium test automation, it will stop the execution
of the script for the time specified in the script, irrespective of the fact that the element on the
web page has been found. Selenium waits do not wait for the complete duration of time. If the
WebDriver is able to find the element before the specified time duration, it moves on to the
next line of code. This helps in reducing the overall time of script execution by a considerable
margin.
Additional:

Selenium setSpeed() is basically used to set a specific speed of execution. When running a script in
Selenium, there is no delay by default. With the help of setSpeed(), we can set the length of delay (in
milliseconds) which will then be followed by each execution in that Selenium script.

***Set speed is deprecated now

Selenium Wait – Implicit, Explicit and Fluent Waits


ByKrishna RungtaUpdatedOctober 29, 2022

In Selenium, “Waits” play an important role in executing tests. In this tutorial, you will learn various
aspects and difference between Implicit and Explicit wait in Selenium.

In this tutorial, you will learn about different types of waits in Selenium:

• Why Do We Need Waits In Selenium?


• Implicit Wait
• Explicit Wait
• Fluent Wait
• Difference Between Implicit Wait Vs Explicit Wait

Why Do We Need Waits In Selenium?


Most of the web applications are developed using Ajax and Javascript. When a page is loaded by the
browser the elements which we want to interact with may load at different time intervals.

Not only it makes this difficult to identify the element but also if the element is not located it will throw an
“ElementNotVisibleException” exception. Using Selenium Waits, we can resolve this problem.

Let’s consider a scenario where we have to use both implicit and explicit waits in our test. Assume that
implicit wait time is set to 20 seconds and explicit wait time is set to 10 seconds.
Suppose we are trying to find an element which has some “ExpectedConditions “(Explicit Wait), If the
element is not located within the time frame defined by the Explicit wait(10 Seconds), It will use the time
frame defined by implicit wait(20 seconds) before throwing an “ElementNotVisibleException“.

Selenium Web Driver Waits

1. Implicit Wait
2. Explicit Wait

Implicit Wait in Selenium


The Implicit Wait in Selenium is used to tell the web driver to wait for a certain amount of time before it
throws a “No Such Element Exception”. The default setting is 0. Once we set the time, the web driver will
wait for the element for that time before throwing an exception.
Selenium Web Driver has borrowed the idea of implicit waits from Watir.

In the below example we have declared an implicit wait with the time frame of 10 seconds. It means that if
the element is not located on the web page within that time frame, it will throw an exception.

To declare implicit wait in Selenium WebDriver:

The default time for Implicit wait is zero and it keeps polling for the required element after every 500
milliseconds

Implicit Wait syntax:


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

package guru.test99;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class AppTest {

protected WebDriver driver;


@Test
public void guru99tutorials () throws InterruptedException
{
System.setProperty ("webdriver.chrome.driver",".\\chromedriver.exe" );
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;
String eTitle = "Demo Guru99 Page";
String aTitle = "" ;
// launch Chrome and redirect it to the Base URL
driver.get("http://demo.guru99.com/test/guru99home/" );
//Maximizes the browser window
driver.manage().window().maximize() ;
//get the actual value of the title
aTitle = driver.getTitle();
//compare the actual title with the expected title
if (aTitle.equals(eTitle))
{
System.out.println( "Test Passed") ;
}
else {
System.out.println( "Test Failed" );
}
//close browser
driver.close();
}
}
Explanation of Code

In the above example,

Consider Following Code:

driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;
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 in Selenium


The Explicit Wait in Selenium is used to tell the Web Driver to wait for certain conditions (Expected
Conditions) or maximum time exceeded before throwing “ElementNotVisibleException” exception. It is an
intelligent kind of wait, but it can be applied only for specified elements. It gives better options than implicit
wait as it waits for dynamically loaded Ajax elements.
Once we declare explicit wait we have to use “ExpectedConditions” or we can configure how frequently
we want to check the condition using Fluent Wait. These days while implementing we are
using Thread.Sleep() generally it is not recommended to use
In the below example, we are creating reference wait for “WebDriverWait” class and instantiating using
“WebDriver” reference, and we are giving a maximum time frame of 20 seconds.

Explicit Wait syntax:


WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
package guru.test99;

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.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class AppTest2 {


protected WebDriver driver;
@Test
public void guru99tutorials() throws InterruptedException
{
System.setProperty ("webdriver.chrome.driver",".\\chromedriver.exe" );
driver = new ChromeDriver();
WebDriverWait wait=new WebDriverWait(driver, 20);
String eTitle = "Demo Guru99 Page";
String aTitle = "" ;
// launch Chrome and redirect it to the Base URL
driver.get("http://demo.guru99.com/test/guru99home/" );
//Maximizes the browser window
driver.manage().window().maximize() ;
//get the actual value of the title
aTitle = driver.getTitle();
//compare the actual title with the expected title
if (aTitle.contentEquals(eTitle))
{
System.out.println( "Test Passed") ;
}
else {
System.out.println( "Test Failed" );
}
WebElement guru99seleniumlink;
guru99seleniumlink= wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(
"/html/body/div[1]/section/div[2]/div/div[1]/div/div[1]/div/div/div/div[2]/div[2]/div/div/div/div/div[1]/div/div/a/i"))
);
guru99seleniumlink.click();
}

Explanation of Code

Consider Following Code:

WebElement guru99seleniumlink;
guru99seleniumlink =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/section/div[2]/div/div
[1]/div/div[1]/div/div/div/div[2]/div[2]/div/div/div/div/div[1]/div/div/a/i")));
guru99seleniumlink.click();
In this WebDriver wait example, wait for the amount of time defined in the “WebDriverWait” class or the
“ExpectedConditions” to occur whichever occurs first.

The above Java code states that we are waiting for an element for the time frame of 20 seconds as
defined in the “WebDriverWait” class on the webpage until the “ExpectedConditions” are met and the
condition is “visibilityofElementLocated“.

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

1. alertIsPresent()
2. elementSelectionStateToBe()
3. elementToBeClickable()
4. elementToBeSelected()
5. frameToBeAvaliableAndSwitchToIt()
6. invisibilityOfTheElementLocated()
7. invisibilityOfElementWithText()
8. presenceOfAllElementsLocatedBy()
9. presenceOfElementLocated()
10. textToBePresentInElement()
11. textToBePresentInElementLocated()
12. textToBePresentInElementValue()
13. titleIs()
14. titleContains()
15. visibilityOf()
16. visibilityOfAllElements()
17. visibilityOfAllElementsLocatedBy()
18. visibilityOfElementLocated()

Fluent Wait in Selenium


The Fluent Wait in Selenium is used to define maximum time for the web driver to wait for a
condition, as well as the frequency with which we want to check the condition before throwing an
“ElementNotVisibleException” exception. It checks for the web element at regular intervals until the object
is found or timeout happens.
Frequency: Setting up a repeat cycle with the time frame to verify/check the condition at the regular
interval of time

Let’s consider a scenario where an element is loaded at different intervals of time. The element might
load within 10 seconds, 20 seconds or even more then that if we declare an explicit wait of 20 seconds. It
will wait till the specified time before throwing an exception. In such scenarios, the fluent wait is the ideal
wait to use as this will try to find the element at different frequency until it finds it or the final timer runs
out.

Fluent Wait syntax:


Wait wait = new FluentWait(WebDriver reference)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);
Above code is deprecated in Selenium v3.11 and above. You need to use

Wait wait = new FluentWait(WebDriver reference)


.withTimeout(Duration.ofSeconds(SECONDS))
.pollingEvery(Duration.ofSeconds(SECONDS))
.ignoring(Exception.class);

package guru.test99;

import org.testng.annotations.Test;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

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.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class AppTest3 {


protected WebDriver driver;
@Test
public void guru99tutorials() throws InterruptedException
{
System.setProperty ("webdriver.chrome.driver",".\\chromedriver.exe" );
String eTitle = "Demo Guru99 Page";
String aTitle = "" ;
driver = new ChromeDriver();
// launch Chrome and redirect it to the Base URL
driver.get("http://demo.guru99.com/test/guru99home/" );
//Maximizes the browser window
driver.manage().window().maximize() ;
//get the actual value of the title
aTitle = driver.getTitle();
//compare the actual title with the expected title
if (aTitle.contentEquals(eTitle))
{
System.out.println( "Test Passed") ;
}
else {
System.out.println( "Test Failed" );
}

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)


.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement clickseleniumlink = wait.until(new Function<WebDriver, WebElement>(){

public WebElement apply(WebDriver driver ) {


return
driver.findElement(By.xpath("/html/body/div[1]/section/div[2]/div/div[1]/div/div[1]/div/div/div/div[2]/div[2]/div/
div/div/div/div[1]/div/div/a/i"));
}
});
//click on the selenium link
clickseleniumlink.click();
//close~ browser
driver.close() ;
}
}
Explanation of Code

Consider Following Code:

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)


.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
In the above example, we are declaring a fluent wait with the timeout of 30 seconds and the frequency is
set to 5 seconds by ignoring “NoSuchElementException”

Consider Following Code:

public WebElement apply(WebDriver driver) {


return
driver.findElement(By.xpath("/html/body/div[1]/section/div[2]/div/div[1]/div/div[1]/div/div/div/div[2]/div[2]/div/
div/div/div/div[1]/div/div/a/i"));
We have created a new function to identify the Web Element on the page. (Ex: Here Web Element is
nothing but the Selenium link on the webpage).

Frequency is set to 5 seconds and the maximum time is set to 30 seconds. Thus this means that it will
check for the element on the web page at every 5 seconds for the maximum time of 30 seconds. If the
element is located within this time frame it will perform the operations else it will throw an
“ElementNotVisibleException”

Also Check:- Selenium IDE Tutorial for Beginners

Difference between Implicit Wait Vs Explicit Wait


Following is the main difference between implicit wait and explicit wait in Selenium:

Implicit Wait Explicit Wait

• Implicit Wait time is applied to all • Explicit Wait time is applied only to those elements which are
the elements in the script • intended by us

• In Implicit Wait, we
• In Explicit Wait, we need to specify “ExpectedConditions” on the
need not specify
element
“ExpectedConditions” on the
• to be located
element to be located

• It is recommended to use when the • It is recommended to use when the elements are taking long time to
elements are located with the time load and also for verifying the property of the element
frame specified in Selenium implicit like(visibilityOfElementLocated,
wait elementToBeClickable,elementToBeSelected)

Conclusion:
Implicit, Explicit and Fluent Wait are the different waits used in Selenium. Usage of these waits are totally
based on the elements which are loaded at different intervals of time. It is always not recommended to
use Thread.Sleep() while Testing our application or building our framework.

Pageload timeout:

The pageLoadTimeout is the method used to set the time for the entire page load prior to throwing an
exception. If the timeout time is set to negative, then the time taken to load the page is endless.
This timeout is generally used with the navigate and manage methods.

Syntax
driver.manage().timeouts().pageLoadTimeout(4, TimeUnit.SECONDS);

Example

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class PageLoadWt{
public static void main(String[] args)
throws InterruptedException{
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//set time for page load
driver.manage().timeouts().pageLoadTimeout(4, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
driver.quit();
}
}

The implicitlyWait is the method applied to the webdriver to wait for elements to be available in the
page. It is a global wait to every element. NoSuchElementException is thrown if an element is still not
available after the wait time has elapsed.

Syntax
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

Example

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ImplicitWt{
public static void main(String[] args)
throws InterruptedException{
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//set implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
driver.quit();
}
}

Selenium webdriver Theory:

https://www.guru99.com/introduction-to-selenium.html

What is Selenium?
Selenium is a free (open-source) automated testing framework used to validate web applications across
different browsers and platforms. You can use multiple programming languages like Java, C#, Python, etc
to create Selenium Test Scripts. Testing done using the Selenium testing tool is usually referred to
as Selenium Testing.
Selenium Tool Suite
Selenium Software is not just a single tool but a suite of software, each piece catering to different
Selenium QA testing needs of an organization. Here is the list of tools

• Selenium Integrated Development Environment (IDE)


• Selenium Remote Control (RC)
• WebDriver
• Selenium Grid
At the moment, Selenium RC and WebDriver are merged into a single framework to form Selenium 2.
Selenium 1, by the way, refers to Selenium RC.
Summary

• The entire Selenium Software Testing Suite is comprised of four components:


• Selenium commands are of three types: Actions, Accessors, and Assertions.

Selenium IDE, a Firefox and chrome add-on that you can only use in creating relatively simple test cases
and test suites. (Supports exporting code to Java, C#, python, Ruby.) Selenium IDE has 7 components:
Menu Bar, Tool Bar, Address Bar, Test Case Pane, Test Script Editor Box, Start/Stop Recording
Button, Log, and Reference Pane.
• Selenium Remote Control, also known as Selenium 1, is the first Selenium tool that
allowed users to use programming languages in creating complex tests.
• WebDriver, is the newer breakthrough that allows your test scripts to communicate
directly to the browser, thereby controlling it from the OS level.
• Selenium Grid is also a tool that is used with Selenium RC to execute parallel tests
across different browsers and operating systems.
• Selenium RC and WebDriver was merged to form Selenium 2.
• Selenium is more advantageous than Microfocus UFT One in terms of costs and flexibility.
• There are total locators in selenium which are as follows: ID, Name, Class Name, Tag Name,
Link Text, Partial Link Text, CSS Selector, XPath.

Selenium Limitations
o Selenium does not support automation testing for desktop applications.
o Selenium requires high skill sets in order to automate tests more effectively.
o Since Selenium is open-source software, you have to rely on community forums to get your
technical issues resolved.
o We can't perform automation tests on web services like SOAP or REST using Selenium.
o We should know at least one of the supported programming languages to create tests scripts in
Selenium WebDriver.
o It does not have built-in Object Repository like UTF/QTP to maintain objects/elements in
centralized location. However, we can overcome this limitation using Page Object Model.
o Selenium does not have any inbuilt reportingcapability; you have to rely on plug-ins
like JUnit and TestNG for test reports.
o It is not possible to perform testing on images. We need to integrate Selenium with Sikuli for
image based testing.
o Creating test environment in Selenium takes more time as compared to vendor tools like UFT,
RFT, Silk test, etc.
o No one is responsible for new features usage; they may or may not work properly.
o Selenium does not provide any test tool integration for Test Management.

What are the significant changes in upgrades in various Selenium versions?


Selenium 1: Included 3 suite of tools: Selenium IDE, Selenium RC and Selenium Grid. There was no
WebDriver in Selenium v1.

Selenium 2: Selenium WebDriver was introduced in Selenium v2. With the onset of WebDriver,
Selenium RC got deprecated and is not in use since. Older versions of RC is available in the market
though, but support for RC is not available.

Selenium 3: Currently, Selenium v3 is in use, and it comprises of IDE, WebDriver and Grid.

IDE is used for recording and playback of tests, WebDriver is used for testing dynamic web applications
via a programming interface and Grid is used for deploying tests in remote host machines.
Selenium4

https://www.softwaretestinghelp.com/new-features-in-selenium-4/

Important Architecture Related Changes


#1) Supports removed for some browsers: Now, they have removed the supports for the browsers
Opera and Phantom JS. Opera users can use the Chrome browser, whereas Phantom JS users can use
Chrome or Firefox in headless mode.
#2) Optimized Selenium Grid: Selenium Grid was developed long back in 2011.
Selenium 4 has come up with new architecture to remove the issues which occurred earlier during
installation and configuration, also during the connection between the hub and node machine.

Let’s understand in brief about the Selenium Grid, which contains two major components:
• Node: It is used to execute tests on individual computer systems. There can be multiple
nodes in a grid.
• Hub: It is the central point from where it controls all the machines present in the network,
and it contains only one hub which helps in allocating test execution to different nodes.
But in Selenium 4, Grid is very flexible. It allows us to test the cases against multiple browsers, browsers
of different versions, and also on different Operating systems. Even now, there is no need for a setup to
start hub and nodes individually once the user starts the server, the Grid automatically works as both
nodes and hub.

It also supports advanced tools like Docker, AWS, Azure, and much more, useful in the DevOps process.
Now Grid has a more user-friendly UI and contains relevant information related to the session, running,
capacity, etc.

>> Click here for more information.


#3) Standardized Documentation: Documents play an essential role for any user, and Selenium
documents were not updated since Selenium 2.0.
With Selenium 4, they have updated all the official documents related to Selenium that include web driver,
Grid, and IDE to explain the latest changes.

#4) Improvement in Selenium 4 IDE: Selenium IDE is a record and playback tool that is used for user
interaction with the browser, and the new version of IDE is available with more features
These features include:
• It improves the browser support. Now with a new version, any browser vendor can easily
plug into the latest Selenium IDE.
• CLI Runner will be based on NodeJS, not the HTML-based runner, and it supports the
parallel execution from which it provides the report with the total number of test cases
passed/failed along with execution time taken.
#5) Better Monitoring: Logging and request tracing process are now improved to make a better grip on
the debugging process for automation engineers as it is not limited to DevOps only.
Features Of Selenium 4
The features are as follows:
#1) Capture screenshot of specific web element:
Earlier, users can take a screenshot of the entire page as there was no provision to take the screenshot
of the specific web element. But with Selenium 4, users can take the screenshot of a specific web
element.

Please find the below code:


WebElement logo=driver.Findelement (By.xpath(“//div[@id=’divLogo’]//img”));

File file=logo.getScreenshotAs(OutputType.FILE);

File destFile =new File(“logo.png”);

FileUtils.copyFile(file,destfile);

#2) Open the new tab on the browser:


Now, in Selenium 4, the user can open a URL in a new tab along with the existing tab.

For Example: If the user wants to open 2 URLs in two different tabs at the same time, the user can do
that with the Selenium 4.
Please find the below code for reference:
driver.get(https://www.google.com/);

driver.switchTo().newWindow(WindowType.TAB);
driver.navigate().to(https://www.crmpro.com/);

#3) Open a new window on the browser:


Using Selenium 4, the users can also open the new window on the same browser.

For Example, if the user wants to access two applications in the same browser, the user can now do this.
Please find the below code for reference:
driver.get(https://www.google.com/);

driver.switchTo().newWindow(WindowType.WINDOW);

driver.navigate().to(https://www.crmpro.com/);

#4) Object Location:


Now with Selenium 4, users can achieve the coordinates, dimension, height, width, etc. as the location of
the web elements or object.

Please find the below code for your reference:


WebElement logo1=driver.Findelement(By.xpath(“//div[@id=’divLogo’]//img”));

System.out.println(“Height:” +logo.getRect().getDimension().getHeight());

System.out.println(“Height:” +logo.getRect().getDimension().getWidth());

System.out.println(“X Location: “ +Logo.getRect().getX());

System.out.println(“Y Location: “ +Logo.getRect().getY());

#5) Relative Locators:


These are also known as Friendly Locators, and this functionality is being added to find out the element
which is present nearby to other web element or, we can say that it can find the web elements based on
GUI location.

There are five locators added in Selenium 4:


• below(): Web element located below for the specified element.
• toLeftOf() : Target web element which is present to the left of specified element.
• toRightOf(): Target web element which is presented to the right of a specified element.
• above(): Web element located above for the specified element.
• near() : Target web element which is away(approx. 50 pixels) from the specified element.
Note: All the above relative locators method support “withTagName” method.
The below example is for the toLeftof() and below() locators:
WebElement book;

book = driver.Findelement(RelativeLocators.withTagName(“li”).toLeftOf(By.id(“pid1”))

.below(By.id(“pid2”)));

String id1=book.getAttribute (“id1”);

The below example is for the toRightOf() and above() locators:


WebElement book1;

book1 = driver.Findelement(RelativeLocators.withTagName(“li”).toRightOf(By.id(“pid1”))
.above(By.id(“pid2”)));

String id2=book1.getAttribute (“id2”);

#6) Chrome Dev tools:


In the new version of Selenium, they have made some internal changes in the API. Earlier in Selenium 3,
the Chrome driver extends directly to the Remote Web Driver class. But now in Selenium 4, Chrome
driver class extends to Chromium Driver. Chromium Driver class has some predefined methods to access
the dev tool.

Note: Chromium Driver extends the Remote Web driver class.


By using the API, we can perform the following operations:
• Enable Network Offline
• Enable Network Online
• Get Console Logs
• Load Insure Web Site
Conclusion
In this tutorial, we have covered the introduction to the new version of Selenium 4, some upcoming
features related to Selenium Grid, IDE, and Selenium WebDriver.

We have also seen a brief description of the Relative Locators, Chrome dev tools. We can expect a lot
from the Selenium 4, be it the browser support, the documentation, or the UI.

Author: This article is written by Akanksha K who has 7+ years of experience in Software Quality and
building Test Frameworks.

Webdriver Commands:
Navigation commands
Webelement commands,

What is Web Element?


The term web element refers to a HTML element. The HTML documents are composed
of HTML elements. It consists a start tag, an end tag and the content in between. For
instance, a HTML element is written as: "<tagname> content </tagname>"

In WebDriver, we have several commonly used web element commands and actions.
The following screenshot displays the eclipse web element command panel.
Submit() vs click()

https://www.tutorialspoint.com/selenium-webdriver-submit-vs-click

The click() and submit() functions are quite similar in terms of functionalities. However there are minor
differences. Let us discuss some differences between them.

The submit() function is applicable only for <form> and makes handling of form easier. It can be used with
any element inside a form. The click() is only applicable to buttons with type submit in a form.

The submit() function shall wait for the page to load however the click() waits only if any explicit wait
condition is provided. If a form has a submit of type button, the submit() method cannot be used. Also, if a
button is outside <form>, then submit() will not work.

Thus we see that click() works for both type buttons irrespective of the fact that the button is inside or
outside of <form>. Let us take up the below form for implementation.

Last End theory

https://www.tutorialspoint.com/testng/testng_ignore_test.htm

https://www.javatpoint.com/testng-groups
https://www.javatpoint.com/testng-interview-questions

Nice to have:

Method declarations(static, public etc)

https://www.geeksforgeeks.org/java-main-method-public-static-void-main-string-args/

Can we execute a java program without main method?


Yes, we can execute a java program without a main method by using a static block.
A static block in Java is a group of statements that gets executed only once when the class is loaded
into the memory by ClassLoader, It is also known as a static initialization block, and it goes into the
stack memory.

Downloading a file:

Summary

• Uploading files in WebDriver is done by simply using the sendKeys() method on the file-select
input field to enter the path to the file to be uploaded.
• WebDriver cannot automate downloading of files on its own.
• The easiest way to download files using WebDriver is to use Wget.
Uploading using Auto IT

AShot API

Ad blocker with chrome options

Set Speed():

//Looks like set speed is only available in IDE

Difference Between Thread.sleep() & Selenium setSpeed()

As we have seen above how to use Thread.sleep() in Java, we understand clearly that it is used to
delay the code execution. setSpeed() has a similar role and is also used to delay the over execution.
Yet, the two functions are different from each other.

Selenium setSpeed() is basically used to set a specific speed of execution. When running a script in
Selenium, there is no delay by default. With the help of setSpeed(), we can set the length of delay ( in
milliseconds) which will then be followed by each execution in that Selenium script.

To put it plainly, Thread.sleep() makes the WebDriver wait for a specific time before execution and
this happens only once. On the other hand, setSpeed() sets the desir ed speed of execution or delays
execution by a specified amount of time before each operation.

Java basics:

https://www.javatpoint.com/java-basics

https://www.javatpoint.com/java-oops-concepts

https://www.javatpoint.com/java-naming-conventions

Simula is considered the first object-oriented programming language. The programming paradigm where
everything is represented as an object is known as a truly object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming language.

Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means


we organize our software as a combination of different types of objects that incorporate both data and
behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software development and


maintenance by providing some rules.
Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Polymorphism

If one task is performed in different ways, it is known as polymorphism. For example: to convince the
customer differently, to draw something, for example, shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.

What is the difference between an object-oriented programming language and object-based programming
language?

Object-based programming language follows all the features of OOPs except Inheritance. JavaScript and
VBScript are examples of object-based programming languages.

CamelCase in Java naming conventions

Java follows camel-case syntax for naming the class, interface, method, and variable.

If the name is combined with two words, the second word will start with uppercase letter always such as
actionPerformed(), firstName, ActionEvent, ActionListener, etc.

Instance variable in Java

A variable which is created inside the class but outside the method is known as an instance variable.
Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or
instance is created. That is why it is known as an instance variable.

New keyword in Java

The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.
3 Ways to initialize object

There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor

What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:

o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.

Static vs instance method

To call static method we don’t need to create an object, for instance method we need to create an object
to call the method.
There are two types of instance method:

o Accessor Method
o Mutator Method

Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor method.
We can easily identify it because the method is prefixed with the word get. It is also known as getters. It
returns the value of the private field. It is used to get the value of the private field.

Example

1. public int getId()


2. {
3. return Id;
4. }

Mutator Method: The method(s) read the instance variable(s) and also modify the values. We can easily
identify it because the method is prefixed with the word set. It is also known as setters or modifiers. It
does not return anything. It accepts a parameter of the same data type that depends on the field. It is
used to set the value of the private field.

Example

1. public void setRoll(int roll)


2. {
3. this.roll = roll;

Abstract Method

The method that does not has method body is known as abstract method. In other words, without an
implementation is known as abstract method. It always declares in the abstract class. It means the class
itself must be abstract if it has abstract method. To create an abstract method, we use the
keyword abstract.

Contructors:

https://www.javatpoint.com/java-constructor

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Difference between constructor and method in Java

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

A constructor is used to initialize the state of A method is used to expose the


an object. behavior of an object.

A constructor must not have a return type. A method must have a return
type.

The constructor is invoked implicitly. The method is invoked


explicitly.

The Java compiler provides a default The method is not provided by


constructor if you don't have any constructor the compiler in any case.
in a class.

The constructor name must be same as the The method name may or may
class name. not be same as the class name.

Q) Does constructor return any value?

Yes, it is the current class instance (You cannot use return type yet it returns a value)

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling a method, etc. You can perform any operation in the
constructor as you perform in the method.

Is there Constructor class in Java?

Yes.

What is the purpose of Constructor class?

Java provides a Constructor class which can be used to get the internal information of a constructor in the
class. It is found in the java.lang.reflect package.
Collections and Return types”

https://www.javatpoint.com/collections-in-java

Maven?

https://www.javatpoint.com/selenium-maven

Additional listeners

Email [email protected]

1) Select the operating


system which is NOT
Correct: Unix
supported by Selenium
IDE.

2) The Selenium RC is Correct: To run your test against different browsers (except
used HtmlUnit) on different operating systems.

3) Out of the following


which can only test web Correct: Selenium
applications

4) Select the component


which is NOT part of Correct: Selenium Web
Selenium suite.

5) Select the component


which is NOT part of Correct: ASP
Selenium suite.

6) Select the name


which is NOT the type of Correct: Password
the locaters.

7) The Web driver is Correct: To execute tests on the HtmlUnit browser.


used

8) The Selenium IDE is


Correct: To test a web application against Firefox only.
used

9)Select the Browser


which is supported by Correct: Mozilla Firefox
Selenium IDE

10)Selenium IDE stands


Correct: Selenium Integrated Development Environment
for

11) Is Web Driver a


component of the Correct: Yes
Selenium?

12) Select the command


which is NOT a type of
Correct: Wait
assertion in Selenium
IDE.

13) Select the method


which selects the option Correct: selectByIndex()
at the given index.

14) The Selenium can Correct: only test web applications

15) The Selenium Correct: Cannot access elements outside of the web application
under test

16) Can Google chrome


be supported by Correct: No
Selenium IDE?

17) Can Unix operating


system be supported by Correct: No
Selenium IDE?

18)Which command can


be used to enter values Correct: sendKeys()
onto text boxes?
19)Select the language
which is supported by
Correct: Perl
The Selenium Web
Driver

20)Which Selenium
component supports All Correct: Selenium WebDriver
Operating System?

21)Select the command


in Selenium IDE used to
Correct: Open
open a page using the
URL.

22)Select the command


in Selenium IDE used to
Correct: HTML format.
open a page using the
URL.

23)The Actions
Correct: are commands that directly interact with page elements.
commands

24)Select the command


which is used to check
Correct: verifyElementPresent
the presence of a
certain element.

25)Select the command


which is used to print a
Correct: The 'echo' command
string value or a variable
in Selenium IDE.

26)Which component of
Selenium can create Correct: Web driver
customized test results.

27)Select the command


which is used to
compare the contents of Correct: verifyTable
a table with expected
values.
28)Select the command
which is used to
compare the contents of Correct: waitForElementPresent
a table with expected
values.

29)Select the command


that will NOT wait for a
new page to load before Correct: selectAndType
moving onto the next
command.

30)Select the command


which is used to pause
Correct: waitForPageToLoad
execution until the page
is loaded completely.

31)What can be used to


test Flex/Flash
Correct: FlexUISelenium
applications using
Selenium

32)Select the command


which is used to
compare the actual Correct: verifyTitle
page title with an
expected value.

33)Select the command


which is NOT used in
Correct: verifyElementRight
verifying page elements
.

34)Select the tab which


gives feedback and
Correct: Reference
other useful information
when executing tests.

35)What is TestNG? Correct: TestNextGeneration

36)Select the variation Correct: By.cssSelector


which finds elements
based on the driver's
underlying CSS selector
engine in Web driver
Selenium.

37)Select the variation


which locates elements
by the value of the Correct: By.name
"name" attribute in Web
driver Selenium

38)Select the tab that


shows which command
Correct: Info
Selenium IDE is
currently executing.

39)Which is a faster
component between the
Correct: Selenium Web driver
SeleniumWeb driver
and Selenium RC?

40)Select the variation


which locates elements
by the value of their "id" Correct: By.id
attribute in Web Driver
Selenium

41)Select the Get


command which fetches
the inner text of the Correct: getText()
element that you specify
in Web driver Selenium.

42)Which Navigate
command takes you
forward by one page on Correct: navigate().forward()
the browser's history in
Web driver Selenium.

43)Which method is
used when you want to Correct: isSelected()
verify whether a certain
check box, radio button,
or option in a drop-down
box is selected in Web
driver Selenium

44)Which Component is
used to run multiple
tests simultaneously in Correct: Selenium Grid
different browsers and
platforms?

45)Select the View


which shows your script Correct: The Source View
in HTML format.

46)Select the method


which clears all selected
Correct: deselectAll()
entries in Web driver
Selenium.

47)Method which
selects the option which
displays the text Correct: selectByVisibleText()
matching the parameter
passed to it

48)Out of the following


which is NOT a wait Correct: waitForActive
command.

49)Select the command


which retrieves the alert
message and stores it in Correct: storeAlert
a variable that you will
specify.

50)Select the method


which performs a
Correct: contextClick()
context-click at the
current mouse location.
lap check and ppt quick read

xpaths,actions and robot class

tooltip

revise waits syntax

revise assert syntaxs

Assert and Verify:

https://www.browserstack.com/guide/verify-and-assert-in-selenium

Assertions (also known as Asserts)


The word Assert means to state a fact or belief confidently or forcefully. In Selenium, Asserts are
validations or checkpoints for an application. Assertions state confidently that application behavior is
working as expected. Asserts in Selenium validate the automated test cases that help testers understand
if tests have passed or failed.
Types of Assertions

• Hard Assertions

• Soft Assertions (Verify Method)

Hard Asserts vs Soft Asserts

Hard Assertions Soft Assertions

Test Execution will be aborted if the assert condition is not Test execution will continue till the end of the test case
met even if the assert condition is not met

Does not have to invoke any methods to capture the To view assertions result at the end of the test, the teste
assertions has to invoke assertAll()

Hard Assertions
Hard Assertions are ones in which test execution is aborted if the test does not meet the assertion
condition. The test case is marked as failed. In case of an assertion error, it will throw the
“java.lang.AssertionError” exception.
Let’s explore different types of hard assertions with examples.
assertEquals() is a method that takes a minimum of 2 arguments and compares actual results with
expected results. If both match, the assertion is passed, and the test case is marked as
passed. assertEquals() can compare Strings, Integers, Doubles, and many more variables, as shown in
the image below.

Closing Notes

• Hard and Soft Assertions are very important for designing and running Selenium Webdriver tests.

• They are instrumental in verifying application behavior at critical stages.

• By using assertions, testing teams can determine if an application is working as expected.

• They can also save teams the trouble of running tests that don’t need to be run if a condition is
not met.
• To use soft asserts , we need to create an object using softassert class and then call the
assertion commands using the object created.
Selenium IDE:

https://www.qafox.com/new-selenium-ide-commands-selenese/

https://www.javatpoint.com/selenium-ide-commands

https://www.javatpoint.com/selenium-ide-commands

https://www.javatpoint.com/selenium-ide-features

Name description Command target Value


open the given Application base URL in the
1. open
browser. open /
type any given text into the text fields in the
2. type
application. type name=q search item
xpath=//button[@
3. click
click on any UI element in the application. click class=’dropbtn’]
click on any UI element at the given x & y xpath=//button[@
4. click at
coordinate position of the UI element. click at class=’dropbtn’] 10,20
xpath=//button[te
5. double
xt()=’ Double click
click
double click on any UI element. double click Here ‘]
6. double double click on any UI element at the given x & double click xpath=//button[@
click at y coordinate position of the UI element. at class=’dropbtn’] 10,20
7. set window set window
size resize the browser window. size 300x200
8. close close the browser window. close
9. select select an option from the dropdown field. select id=drop1 Label=doc4
10. add select options from the multi-selection box add
selection field.(repeat multiple times) selection id=multiselect1 Value text
remove the selection of selected options in the
11. remove
multi-selection box field.(repeat to remove remove
selection
multiple values) selection id=multiselect1 Value text
12. check select the radio button. Check id=radio1
13. uncheck un select the radio button. Uncheck id=radio1
14. assert Title text to be
title check the title of the current page. assert title validated
Title text to be
15. verify title
check the title of the current page. verify title validated
check the text on the UI element (i.e. The text
16. assert
between the HTML tags of the located UI
text
element) assert text Id=button2 Button2
17. verify text check the text on the UI element verify text Id=button2 Button2
check that the given text is not available on the assert not Id=button2 Button2
18. assert not UI element. (i.e. The text between the HTML text
text tags of the located UI element)
19. verify not check that the given text is not available on the verify not
text UI element text Id=button2 Button2
xpath=//input[@cl
20. assert
ass=’gsc-search-
value
value attribute value of the given UI element. assert value button’] text value
xpath=//input[@cl
21. verify
ass=’gsc-search-
value
value attribute value of the given UI element. verify value button’] text value
assert
22. assert
check whether the given option is selected in selected
selected value
the dropdown field. value Id=button2 textvalue
verify
23. verify
check whether the given option is selected in selected
selected value
the dropdown field. value Id=button2 textvalue
assert not
24. assert not
check whether the given option is not in selected
selected value
the selected state in dropdown field. value id=drop1 textvalue
verify not
25. verify not check whether the given option is not in selected
selected value
the selected state in dropdown field. value id=drop1 textvalue
check whether the given option is selected in assert
26. assert
the dropdown field using its label text or display selected
selected label
text. label id=drop1 textvalue
check whether the given option is selected in verify
27. verify
the dropdown field using its label text or display selected
selected label
text. label id=drop1 textvalue
28. assert check whether the given checkbox is in assert
checked selected state. checked id=drop2 textvalue
29. verify check whether the given checkbox is in verify
checked selected state. checked id=drop3 textvalue
30. assert not check whether the given checkbox option is not assert not
checked selected. checked id=checkbox2
31. verify not check whether the given checkbox option is not verify not
checked selected. checked id=checkbox2
32. assert check whether the given field is in an editable assert
editable state. editable name=q
33. verify check whether the given field is in an editable verify
editable state. editable name=q
34. assert not check whether the given field is in a non- assert not
editable editable state. editable id=rotb
35. verify not check whether the given field is in a non- verify not
editable editable state. editable id=rotb
36. assert check whether the given UI element is assert
element present present on the page. element id=but2
present
assert
37. verify
check whether the given UI element is element
element present
present on the page. present id=but2
38. assert assert
element not check whether the given UI element is not element not
present present on the page. present id=buttonxyz
39. verify verify
element not check whether the given UI element is not element not
present present on the page. present id=buttonxyz
40. assert check whether the required alert text is
alert displayed on the page. assert alert text to validate
41. assert check whether the required confirmation dialog assert
confirmation is displayed on the page. confirmation text to validate
42. webdriver webdriver
choose ok on choose ok on
visible select the ‘OK’ button on the displayed visible
confirmation confirmation dialog. confirmation
webdriver
43. webdriver
choose
choose cancel
cancel on
on visible
select the ‘CANCEL’ button on the displayed visible
confirmation
confirmation dialog. confirmation
to plan for cancelling the confirmation dialog choose
44. choose
before it is displayed. i.e. Once the confirmation cancel on
cancel on next
dialog is displayed on the page, it will be next
confirmation
cancelled. confirmation
to plan for accepting the confirmation dialog
45. choose ok
before it is displayed. i.e. Once the confirmation choose ok
on next
dialog is displayed on the page, it will be on next
confirmation
accepted. confirmation
46. assert check whether the prompt dialog is displayed assert
prompt during execution. prompt text to validate
47. answer on is for providing the answer to be entered into answer on
next prompt the prompt before the prompt is displayed. next prompt text to enter
webdriver
48. webdriver
answer on
answer on
enter the answer into the prompt when the visible
visible prompt
prompt is actually displayed. prompt text to enter
49. choose to plan for cancelling the prompt before it is choose
cancel on next displayed. i.e. Once the prompt is displayed on cancel on
prompt the page, it will be cancelled. next prompt
webdriver
50. webdriver
choose
choose cancel
cancel on
on visible
to cancel the prompt when it is actually visible
prompt
displayed. prompt
is to pause the execution of the Selenium IDE
Automation script for debugging purpose (i.e.
for identifying the root cause of any problem
51. debugger
and rectifying it)- user needs to manually press
the run/resume button to continue with the
execution debugger
52. select select the required frame before performing
frame any UI element inside it. select frame index=0
drag and
53. drag and
to drag an UI element and drop it at another UI drop to
drop to object
element. object id=draggable id=droppable
text to be
54. echo
print the messages given in Selenium IDE. echo displayed
55. edit new text to be
content change the value of the given UI element. edit content id=button2 updated
56. execute execute alert(“Hello
script execute the JavaScript code in Selenium IDE. script World!”)
perform mouse left click operation, mouse
move at command is to move the holder UI
57. mouse
element to the target element and mouse down
down, mouse
the mouse up command is to release the
move at and
mouse up mouse click to release the so far held UI mouse move atid=draggable
element to the desired element in Selenium id=droppable
mouse up
IDE. id=droppable
left click operation at the given x & y
coordinate position, mouse move
at command is to move the holder UI
58. mouse mouse id=draggable 10,20
element to the target element at the given x
down at, mouse down at
& y coordinate position and the mouse
move at and
mouse up at up command is to release the mouse click mouse move id=droppable 11,15
to release the so far held UI element to the at
desired element at given x & y coordinate
position in Selenium IDE. mouse up at id=droppable 8,13
perform mouse the hover action on the mouse over id = home
59. mouse
given UI element. And the purpose of
over and mouse
out the mouse out command is to move the
mouse outside of the hovered UI element. mouseout id=home
pause the execution of Selenium Test for the
60. pause
required time. pause 10000
submit any form on the page say Login, Signup css=form[action$=’
61. submit
forms, etc. submit login’]
62. store store any text into a variable in Selenium IDE. store text to save variable name
retrieve and store the title of the page into a
63. store title variable in Selenium IDE. To refer variable use
${variable name} store title variable name
retrieve and store the count of the UI elements
64. store
located using the given XPath Locating strategy store xpath
xpath count
into a variable in Selenium IDE. count xpath=//a variable name
retrieve and store the value attribute value of
65. store
the located UI element into a variable in store value
value
Selenium IDE. id=rotb variable name
retrieve and store the text between the HTML
66. store text tags of the located UI element into a variable in store text
Selenium IDE. id=pah variable name
retrieve and store the value of the given
67. store
attribute name of the located UI element into a store
attribute
variable in Selenium IDE attribute id=but2@type variable name
check the value stored in a variable is according text to
68. assert
to the expected result. assert variable name validate
check the value stored in a variable is according text to
69. verify
to the expected result. verify variable name validate
wait for the element to get editable. i.e. If any
required element on the application is by
70. wait for default in non-editable state and gets editable
element in some time, we can use wait for element
editable editable command to wait for the element to wait for
get editable, before editing the element
element.(timeunit in milli seconds) editable id=pah 30000
wait for the element to get non-editable.
i.e. If any required element on the
application is by default in editable state
71. wait for
and gets non-editable in some time, we can
element not
editable use wait for element not
editable command to wait for the element wait for
to get non-editable, before editing the element not
element. editable id=pah 30000
wait for the element to get displayed on the
page i.e. If any required element on the
application is by default not displayed and
72. wait for
gets displayed in some time, we can
element visible
use wait for element visible command to wait for
wait for the element to get displayed before element
performing any operation on the element. visible id=pah 30000
wait for the element to get disappear from
the page i.e. If any required element on the
73. wait for
application is by default displayed and then
element not
visible disappear in some time, we can use wait for wait for
element not visible command to wait for element not
the element to disappear from the page. visible id=pah 30000
74. wait for waits for element to be present wait for id=pah 30000
element present element
present
75. wait for wait for
element not element not
present waits for element to not be present present id=pah 30000
{ “glossary”: {
“title”: “example
glossary”,
“GlossDiv”: {
“title”: “S”,
“GlossList”: {
“GlossEntry”: {
“ID”: “SGML”,
“SortAs”: “SGML”,
“GlossTerm”:
“Standard
Generalized
Markup Language”,
76. store json “Acronym”:
“SGML”, “Abbrev”:
“ISO 8879:1986”,
“GlossDef”: {
“para”: “A meta-
markup language,
used to create
markup languages
such as DocBook.”,
“GlossSeeAlso”:
[“GML”, “XML”] },
“GlossSee”:
retrieve and store json content into a variable “markup” } } } } }
in Selenium IDE. store json variable name
modify the default speed of Selenium IDE
77. set speed execution (i.e. 0 seconds) to the required
milliseconds. set speed 5000
press the required keyboard key using any of
78. send keys the below-specified keyboard keycodes: (Scroll name=q
below for different key codes) send keys ${KEY_ENTER}
tab=1
or
79. select title=Basic Web
window Page Title
select or
select or switch to another window. window
store title=omayo
80. store
store the window using its locator i.e. tab index window (QAFox.com)
window handle
or title. handle or tab=1 variable name
execute the JavaScript code snippets in alert(“Hello
81. run script
Selenium IDE. run script World!”)

82. execute
async script execute the async snippet of JavaScript code in execute
Selenium IDE. async script
execute another Selenium IDE Test in the
83. run current Selenium IDE Test. (give the other test
name to run in the target column) run Login
check whether the given condition is true or
false. If the condition results in true, the
Selenium IDE statements inside
the if and end commands will be executed.
84. if and end
If the condition results in false, the Selenium
IDE statements inside
the if and end commands won’t be
executed (i.e. skipped from execution).

85. else

else is the command in Selenium IDE will


be executed when the if condition results in
false.

86. else if

executed when the if condition results in


false and we have another condition to be
validated before going to the else block.
87. times times is one of the commands in
Selenium IDE and we can end it
with end command.

88. while
while is the command in Selenium IDE used
for executing a set of same statements
multiple times until the while condition
becomes false. we can end it
with end command.

89. do and
repeat if
do and repeat if are the command in
Selenium IDE used for executing a set of
same statements multiple times until
the repeat if condition becomes false.

for each is the command in Selenium


90. for each IDE used for executing a set of same
statements multiple times until all the
values in the given array (i.e. multiple set
of values stored in a single variable) are
completed.
Key Code Function

KEY_LEFT Navigation Left

KEY_UP Navigation Up

KEY_RIGHT Navigation Right

KEY_DOWN Navigation Down

KEY_PGUP or KEY_PAGE_UP Page up

KEY_PGDN or KEY_PAGE_DOWN Page down

KEY_BKSP or KEY_BACKSPACE Backspace

KEY_DEL or KEY_DELETE Delete

KEY_ENTER Enter

KEY_TAB Tab

Selenium IDE-Features

Selenium IDE is divided into different components, each having their own features and functionalities.We
have categorized seven different components of Selenium IDE, which includes:
1. Menu Bar
2. Tool Bar
3. Address Bar
4. Test Case Pane
5. Test Script Editor Box
6. Start/Stop Recording Button
7. Log, Reference Pane

Menu bar is positioned at the top most portion of the Selenium IDE interface. The most
commonly used modules of menu bar include:

o Project Name
It allows you to rename your entire project.

o Open Project
It allows you to load any existing project from your personal drives.

AD

o Save Project
It allows you to save the entire project you are currently working on.
2. Tool Bar
The Tool bar contains modules for controlling the execution of your test cases. In
addition, it gives you a step feature for debugging you test cases. The most commonly
used modules of Tool Bar menu include:

o Speed Control Option


It allows you to control the execution speed of your test cases.

o Step Feature
It allows you to "step" through a test case by running it one command at a time.
Use for debugging test cases.

o Run Tests
It allows you to run the currently selected test. When only a single test is loaded
"Run Test" button and "Run all" button have the same effect.
o Run All
It allows you to run the entire test suite when a test suite with multiple test cases
is loaded.

3. Address Bar
This module provides you a dropdown menu that remembers all previous values for
base URL. In simple words, the base URL address bar remembers the previously visited
websites so that the navigation becomes easy later on.

4. Test Case Pane


This module contains all the test cases that are recorded by IDE. In simple words, it
provides the list of all recorded test cases at the same time under the test case pane so
that user could easily shuffle between the test cases.
At the bottom portion of the Test Case Pane, you can see the test execution result
summary which includes the pass/fail status of various test cases.

Test Case Pane also includes features like Navigation panel which allow users to
navigate between test cases and test suites.

5. Test Script Editor Box


Test Script Editor Box displaysall of the test scripts and user interactions that were
recorded by the IDE. Each user interaction is displayed in the same order in which they
are performed. The Editor box is divided into three columns:Command, Target and
Value.
o Command:
Command can be considered as the actual operation/action that is performed on
the browser elements. For instance, if you are opening a new URL, the command
will be 'open'; if you are clicking on a link or a button on the web page, then the
command will be 'clicked'.
o Target:
Target specifies the web element on which the operation has to be performed
along with a locator attribute. For instance, if you are clicking on a button called
javaTpoint, then the target link will be 'javaTpoint'.

o Value:
Value is treated as an optional field and can be used when we need to send some
actual parameters. For instance, if you are entering the email address or password
in a textbox, then the value will contain the actual credentials.
6. Start/Stop Recording Button
Record button records all of the user actions with the browser.

7. Log, Reference Pane


The Log Pane displays the runtime messages during execution. It provides real-time
updates of the actions performed by the IDE. It can be categorized into four types: info,
error, debug and warn.
The reference Pane displays the complete detail of the currently selected selenese
command in the editor.

open:

The purpose of open command in Selenium IDE, is to open the given Application base
URL in the browser.
In this article, I am going t

type:
The purpose of type command in Selenium IDE, is to type any given text into the text
fields in the application.

Selenium IDE - handling Table:

https://www.software-testing-tutorials-automation.com/2013/10/how-to-use-table-commands-
waitfortable.html

https://www.selenium.dev/documentation/legacy/selenium_ide/

"waitForTable" Command

"waitForTable" command will wait for table data for targeted row and column. Selenium will not execute
next command until targeted data not appears in table. It will return '[error] Timed out after 30000ms' if
targeted text will not appear within default timeout and then selenium will go for executing next command.

"storeTable" Command

"storeTable" command will store data of targeted cell of table. Look at the bellow given example for
"waitForTable" and "storeTable" commands.

New Test
Command Target Value
http://only-testing-
open
blog.blogspot.com/2013/10/table.html
waitForTable css=div > table.2.5 Ready!
storeTable css=div > table.0.2 1strow3rdcolumn
echo ${1strow3rdcolumn}
storeTable css=div > table.2.4 3rdrow5thcolumn
echo ${3rdrow5thcolumn}

In above given example, "waitForTable" command will wait for text 'Ready!' in 3rd row and 6th column of
targeted table. Here 'css=div > table.2.5' means 3rd row and 6th column of table. "storeTable" command
will retrieve data from 1st raw and 3rd column of table and store it in variable '1strow3rdcolumn'.
IDE commands eg2

Command Target Value


open /download/
assertTitle Downloads
verifyText //h2 Downloads
assertTable 1.2.1 Selenium IDE
verifyTable 1.2.2 June 3, 2008
verifyTable 1.2.3 1.0 beta 2

*****Table.row.column

You can either use the index or

Locators like this - css=div > table.2.5

The above example first opens a page and then “asserts” that the correct page is loaded
by comparing the title with the expected value. Only if this passes will the following
command run and “verify” that the text is present in the expected location. The test
case then “asserts” the first column in the second row of the first table contains
the expected value, and only if this passed will the remaining cells in that row be
“verified”.

Supported Exports

Currently, export to the following languages and test frameworks is supported.

• C# NUnit
• Java JUnit
• JavaScript Mocha
• Python pytest

Handling Excel - Apache POI:

How to handle excel file using POI (Maven POM


Dependency)

To Read and Write Excel file in Java, Apache provides a very famous library
POI. This library is capable enough to read and write
both XLS and XLSX file format of Excel.

To read XLS files, an HSSF implementation is provided by POI library.

To read XLSX, XSSF implementation of POI library will be the choice. Let’s
study these implementations in detail.

If you are using Maven in your project, the Maven dependency will be
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
Or you can simply download the latest version POI jars from http://poi.apache.org/download.html &
download the latest zip file

Following is a list of different Java Interfaces and classes in POI for reading XLS and XLSX file-

• Workbook: XSSFWorkbook and HSSFWorkbook classes implement this interface.


• XSSFWorkbook: Is a class representation of XLSX file.
• HSSFWorkbook: Is a class representation of XLS file.
• Sheet: XSSFSheet and HSSFSheet classes implement this interface.
• XSSFSheet: Is a class representing a sheet in an XLSX file.
• HSSFSheet: Is a class representing a sheet in an XLS file.
• Row: XSSFRow and HSSFRow classes implement this interface.
• XSSFRow: Is a class representing a row in the sheet of XLSX file.
• HSSFRow: Is a class representing a row in the sheet of XLS file.
• Cell: XSSFCell and HSSFCell classes implement this interface.
• XSSFCell: Is a class representing a cell in a row of XLSX file.
• HSSFCell: Is a class representing a cell in a row of XLS file.

• String - getStringCellValue() [It can be used to read Name of the student from
Excel ].
• Number - getNumericCellValue() [It can be used to read the mobile number of
the student].
• Date - getDateCellValue() [It can be used to read the Date of Birth of the
student].

https://www.toolsqa.com/selenium-webdriver/excel-in-selenium/

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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 java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class WriteToExcel {


public static void main(String args[]) throws IOException {
//set the ChromeDriver path
System.setProperty("webdriver.chrome.driver","E:\\Projects\\chromedriver.exe");

//Create an object of File class to open xls file


File file = new File("E:\\TestData\\TestData.xls");

//Create an object of FileInputStream class to read excel file


FileInputStream inputStream = new FileInputStream(file);

//creating workbook instance that refers to .xls file


HSSFWorkbook wb=new HSSFWorkbook(inputStream);

//creating a Sheet object


HSSFSheet sheet=wb.getSheet("STUDENT_DATA");

//get all rows in the sheet


int rowCount=sheet.getLastRowNum()-sheet.getFirstRowNum();

//Creating an object of ChromeDriver


WebDriver driver = new ChromeDriver();

//Navigate to the URL


driver.get("https://demoqa.com/automation-practice-form");

//Identify the WebElements for the student registration form


WebElement firstName=driver.findElement(By.id("firstName"));
WebElement lastName=driver.findElement(By.id("lastName"));
WebElement email=driver.findElement(By.id("userEmail"));
WebElement genderMale= driver.findElement(By.id("gender-radio-1"));
WebElement mobile=driver.findElement(By.id("userNumber"));
WebElement address=driver.findElement(By.id("currentAddress"));
WebElement submitBtn=driver.findElement(By.id("submit"));

//iterate over all the rows in Excel and put data in the form.
for(int i=1;i<=rowCount;i++) {
//Enter the values read from Excel in firstname,lastname,mobile,email,address
firstName.sendKeys(sheet.getRow(i).getCell(0).getStringCellValue());
lastName.sendKeys(sheet.getRow(i).getCell(1).getStringCellValue());
email.sendKeys(sheet.getRow(i).getCell(2).getStringCellValue());
mobile.sendKeys(sheet.getRow(i).getCell(4).getStringCellValue());
address.sendKeys(sheet.getRow(i).getCell(5).getStringCellValue());

//Click on the gender radio button using javascript


JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", genderMale);

//Click on submit button


submitBtn.click();

//Verify the confirmation message


WebElement confirmationMessage = driver.findElement(By.xpath("//div[text()='Thanks for
submitting the form']"));

//create a new cell in the row at index 6


HSSFCell cell = sheet.getRow(i).createCell(6);

//check if confirmation message is displayed


if (confirmationMessage.isDisplayed()) {
// if the message is displayed , write PASS in the excel sheet
cell.setCellValue("PASS");

} else {
//if the message is not displayed , write FAIL in the excel sheet
cell.setCellValue("FAIL");
}

// Write the data back in the Excel file


FileOutputStream outputStream = new FileOutputStream("E:\\TestData\\TestData.xls");
wb.write(outputStream);

//close the confirmation popup


WebElement closebtn = driver.findElement(By.id("closeLargeModal"));
closebtn.click();

//wait for page to come back to registration page after close button is clicked
driver.manage().timeouts().implicitlyWait(2000, TimeUnit.SECONDS);
}

//Close the workbook


wb.close();

//Quit the driver


driver.quit();
}
}

How to write to a new cell in a new row?

The Apache POI sheet class provides methods to create new rows and then cells in these rows.
Moreover, you can create a new row in an Excel sheet as follows:

HSSFRow row3=sheet.createRow(3);
After the row creates, we can create the cells and input the data in the excel sheet, as shown below-

row3.createCell(0).setCellValue("Diana");
row3.createCell(1).setCellValue("Jane");
row3.createCell(2).setCellValue("Female");
Subsequently, let’s write additional student data in the sheet by creating a new row in our sample Excel:

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteToExcel {


public static void main(String args[]) throws IOException {

//Create an object of File class to open xlsx file


File file = new File("E:\\TestData\\TestData.xls");

//Create an object of FileInputStream class to read excel file


FileInputStream inputStream = new FileInputStream(file);

//creating workbook instance that refers to .xls file


HSSFWorkbook wb=new HSSFWorkbook(inputStream);

//creating a Sheet object using the sheet Name


HSSFSheet sheet=wb.getSheet("STUDENT_DATA");

//Create a row object to retrieve row at index 3


HSSFRow row2=sheet.createRow(3);

//create a cell object to enter value in it using cell Index


row2.createCell(0).setCellValue("Diana");
row2.createCell(1).setCellValue("Jane");
row2.createCell(2).setCellValue("[email protected]");
row2.createCell(3).setCellValue("Female");
row2.createCell(4).setCellValue("8786858432");
row2.createCell(5).setCellValue("Park Lane, Flat C1 , New Jersey");

//write the data in excel using output stream


FileOutputStream outputStream = new FileOutputStream("E:\\TestData\\TestData.xls");
wb.write(outputStream);
wb.close();

Read Configurations from Property File

What is a Property file in Java

.properties files are mainly used in Java programs to maintain project configuration data, database
config or project settings, etc. Each parameter in properties file is stored as a pair of strings, in key-
value pair format, where each key is on one line. You can easily read properties from some file using an
object of type Properties. This is a utility provided by Java itself.

java.util.Properties;

The below is the complete code used for the above test scenario.
package com.objectrepository.demo;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class DemoOR {

public static void main(String[] args) throws IOException {

// Create WebDriver Instance


WebDriver driver;
System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://demo.guru99.com/test/guru99home/");
driver.manage().window().maximize();
// Load the properties File
Properties obj = new Properties();
FileInputStream objfile = new
FileInputStream(System.getProperty("user.dir")+"\\application.properties");
obj.load(objfile);
// Nagigate to link Mobile Testing and Back
driver.findElement(By.xpath(obj.getProperty("MobileTesting"))).click();
driver.navigate().back();
// Enter Data into Form

driver.findElement(By.id(obj.getProperty("EmailTextBox"))).sendKeys("testguru
[email protected]");
driver.findElement(By.id(obj.getProperty("SignUpButton"))).click();
}

Downloading a File using Selenium:


Download File in Selenium WebDriver Using AutoIT

Already we have discussed the AutoIT tool. The same tool is used for downloading files in selenium.
Again, download window changes as per Browsers. So, users have to consider all scenarios to
automate download pop up.
1WinWait("[CLASS:#MozillaDialogClass]","",8)

2Send("!s")

3Sleep(10000)

4Send("{ENTER}")

Save this code and generate .exe file and execute in java code using Runtime.getRuntime().exec().
Again, It is not advisable to use it as it supports only Windows operating system and its external tool.

Download File In Selenium WebDriver Using Robot Class


You can run the below Selenium testing script to download files using Selenium with Java through
Robot class.

public void fileDownload() {

Robot robot = new Robot();

robot.keyPress(KeyEvent.VK_TAB);

robot.keyRelease(KeyEvent.VK_TAB);

robot.keyPress(KeyEvent.VK_ENTER);

robot.keyRelease(KeyEvent.VK_ENTER);

view rawselenium_robot_class.java hosted with ❤ by GitHub

Note: AutoIT and Robot class code could change based on the browser-specific profile set as well as
where you want to save. Moreover, most important is cursor focus. If your download pop up is not in
focus then mostly your code will not work.

Download File In Selenium WebDriver Using The Browser Profile Setting


By leveraging the browser profile setting, you can download files in Selenium WebDriver without
interacting with the download window pop-up. You need to trick the browser profile. Here I have given
a below example for Google Chrome browser and Mozilla Firefox browser.

Add this code into your Selenium Java testing suite.

Google Chrome
System.setProperty("webdriver.chrome.driver", "/Users/neeraj.kumar/Desktop/chromedriver");

ChromeOptions options = new ChromeOptions();

Map<String, Object> prefs = new HashMap<String, Object>();

prefs.put("download.prompt_for_download", false);

options.setExperimentalOption("prefs", prefs);

RemoteWebDriver driver = new ChromeDriver(options);

Mozilla Firefox

FirefoxProfile profile=new FirefoxProfile();


profile.setPreference("browser.helperApps.neverAsk.openFile", "application/octet-stream");

WebDriver driver=new FirefoxDriver(profile);

You might also like