Selenium Wings 1 Notes ( - 1)
Selenium Wings 1 Notes ( - 1)
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.
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.
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.
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.
-Reporting
-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.
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.
package com.guru.testngannotations;
import org.testng.annotations.Test;
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’
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;
@Test (priority = 0)
public void CloseBrowser() {
driver.close();
System.out.println("Closing Google Chrome browser");
}
@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:
Observe that the AccountTest method ran before CloseBrowser even without having any priority because
both sets to priority = 0, and hence, they run alphabetically.
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:
@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.
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.
https://www.javatpoint.com/exclude-include-test-cases-in-testng
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.
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
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.
testng.xml file
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.
https://www.guru99.com/pdf-emails-and-screenshot-of-test-reports-in-selenium.html
https://www.tutorialspoint.com/how-to-use-testng-skipexception
https://www.seleniumeasy.com/testng-tutorials/skip-test-in-testng
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. }
Output:
Tests belonging to multiple Groups
Example:
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"})
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:
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
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:
import org.testng.Assert;
import org.testng.annotations.Test;
@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).
===============================================
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;
@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).
===============================================
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,
o @BeforeSuite
o @BeforeTest
o @BeforeClass
o @BeforeMethod
o @Test
o @AfterMethod
o @AfterClass
o @AfterTest
o @AfterSuite
• 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
@Test(timeOut = 1000)
@Test
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.
import org.testng.Assert;
import org.testng.annotations.Test;
@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());
}
}
===============================================
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.
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:
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
Eg:
@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}};
}
Create testng.xml
Create a testng.xml /work/testng/src to execute Test case(s).
https://www.toolsqa.com/testng/testng-dataproviders/
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@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).
===============================================
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:
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.
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.
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.
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 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.
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;
@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
}
}
testng.xml
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
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.
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.
Method-1: emailable-report.html
Method-2: index.html
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.
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.
• 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:
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("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)");
js.executeScript("arguments[0].scrollIntoView();",Element );
Syntax:
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
WebDriver driver;
@Test
public void ByPixel() {
System.setProperty("webdriver.chrome.driver", "E://Selenium//Selenium_Jars//chromedriver.exe");
driver = new ChromeDriver();
//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();
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;
WebDriver driver;
@Test
public void ByVisibleElement() {
System.setProperty("webdriver.chrome.driver", "G://chromedriver.exe");
driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView();",Element );
“arguments[0]” means first index of page starting at 0.
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();
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;
WebDriver driver;
@Test
public void ScrollHorizontally() {
System.setProperty("webdriver.chrome.driver", "E://Selenium//Selenium_Jars//chromedriver.exe");
driver = new ChromeDriver();
//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)");
scrollto top:
js.executeScript("window.scrollTo(document.body.scrollHeight,0)");
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 );
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();
}
}
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
Runtime.getRuntime().exec("notepad");
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
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();
}
}
Alert and a popup are graphical user interface components used to show the user information in a
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.
https://www.w3schools.com/js/js_popup.asp#:~:text=A%20prompt%20box%20is%20often,Cancel%22%2
0the%20box%20returns%20null
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.
Before handling dropdown in Selenium and controlling drop-down boxes, we must do following two
things:
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.”
Summary:
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
To control drop-down boxes, you must first import the org.openqa.selenium.support.ui.Select package
and then create a Select instance.
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
Syntax
css=tag.class
This strategy uses the HTML tag and a specific attribute of the element to be accessed.
Syntax
css=tag[attribute=value]
css=tag.class[attribute=value]
Syntax
css=tag:contains("inner text")
Summary
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
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"));
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/
Here, parameter buttons are the Button mask. Which, in turn, is a combination of one or more mouse
button masks.
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;
}
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
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.
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;
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"));
The output below clearly states that the background color became transparent after the mouse-over.
driver.get(baseUrl);
WebElement txtUsername = driver.findElement(By.id("email"));
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.
Actions.dragAndDrop(Sourcelocator, Destinationlocator)
In dragAndDrop method, we pass the two parameters –
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;
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");
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.
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;
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"));
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;
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");
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.
// Create an object of actions class and pass reference of WebDriver as a parameter to its constructor.
Actions actions = new Actions(driver);
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.
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;
// Create an object of actions class and pass reference of WebDriver as a parameter to its constructor.
Actions actions = new Actions(driver);
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:
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;
@Test
WebDriver driver ;
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
driver = new FirefoxDriver();
//goto url
driver.get("http://demo.guru99.com/V4/");
this.takeSnapShot(driver, "c://test.png") ;
/**
* @param webdriver
* @param fileWithPath
* @throws Exception
*/
public static void takeSnapShot(WebDriver webdriver,String fileWithPath) throws Exception{
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
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
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.
Go to https://mvnrepository.com/artifact/ru.yandex.qatools.ashot/ashot
Save the file, and Maven will add the jar to your build path
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.
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.
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;
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);
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;
System.setProperty("webdriver.chrome.driver",
"C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.guru99.com/test/guru99home/");
if (diff.hasDiff() == true) {
System.out.println("Images are same");
} else {
System.out.println("Images are different");
}
driver.quit();
}
}
Summary
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.
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
options.setExperimentalOption("useAutomationExtension", false);
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.
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
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;
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:
Chrome Options for running Chrome browser in headless mode can be accomplished by using the
predefined arguments –headless.
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
-right click and download the crx file for the installed extension
Java:
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
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
- 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();
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.
driver.manage().window().maximize();
Set<String>s=driver.getWindowHandles();
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.
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);
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:
Identifying frames:
Frames can be identified by right clicking on them and selecting the option ”This frame”,or inspect and
use //iframe
Handling Frames:
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.
Copy
Confirm
A confirm box is similar to an alert, except the user can also choose to cancel the message. See a
sample confirm.
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.
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.
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.
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()
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.
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.
• 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.
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.
• 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.
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));
/*Verify both texts before ajax call and after ajax call text.*/
Assert.assertNotEquals(textBefore, textAfter);
System.out.println("Ajax Call Performed");
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.
https://seleniumatfingertips.wordpress.com/tag/setposition/
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());
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;
System.setProperty("webdriver.chrome.driver","E:\\selenium_sumit\\chromedriver_win32_2.33\\chromedri
ver.exe");
//WebDriver used to set window position x coordinate = 100 and y coordinate = 200.
driver.manage().window().setPosition(new Point(100,200));
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.
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:
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.
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.
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.
Step 5) Maintenance
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.
• 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.
• Smoke Testing
• Unit Testing
• Integration Testing
• Functional Testing
• Keyword Testing
• Regression Testing
• Data Driven Testing
• Black Box Testing
• 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.
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:
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“.
1. Implicit Wait
2. Explicit Wait
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.
The default time for Implicit wait is zero and it keeps polling for the required element after every 500
milliseconds
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 {
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.
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;
Explanation of 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()
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.
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;
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”
• 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();
}
}
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 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.
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/
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.
#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.
File file=logo.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file,destfile);
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/);
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/);
System.out.println(“Height:” +logo.getRect().getDimension().getHeight());
System.out.println(“Height:” +logo.getRect().getDimension().getWidth());
book = driver.Findelement(RelativeLocators.withTagName(“li”).toLeftOf(By.id(“pid1”))
.below(By.id(“pid2”)));
book1 = driver.Findelement(RelativeLocators.withTagName(“li”).toRightOf(By.id(“pid1”))
.above(By.id(“pid2”)));
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,
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.
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:
https://www.geeksforgeeks.org/java-main-method-public-static-void-main-string-args/
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
Set Speed():
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.
Object-oriented
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.
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.
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.
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.
The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.
3 Ways to initialize object
1. By reference variable
2. By method
3. By constructor
o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.
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
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
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
There are many differences between constructors and methods. They are given below.
A constructor must not have a return type. A method must have a return
type.
The constructor name must be same as the The method name may or may
class name. not be same as the class name.
Yes, it is the current class instance (You cannot use return type yet it returns a value)
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.
Yes.
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]
2) The Selenium RC is Correct: To run your test against different browsers (except
used HtmlUnit) on different operating systems.
15) The Selenium Correct: Cannot access elements outside of the web application
under test
20)Which Selenium
component supports All Correct: Selenium WebDriver
Operating System?
23)The Actions
Correct: are commands that directly interact with page elements.
commands
26)Which component of
Selenium can create Correct: Web driver
customized test results.
39)Which is a faster
component between the
Correct: Selenium Web driver
SeleniumWeb driver
and Selenium RC?
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?
47)Method which
selects the option which
displays the text Correct: selectByVisibleText()
matching the parameter
passed to it
tooltip
https://www.browserstack.com/guide/verify-and-assert-in-selenium
• Hard 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 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
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
86. else if
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.
KEY_UP Navigation Up
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 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.
Test Case Pane also includes features like Navigation panel which allow users to
navigate between test cases and test suites.
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.
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.
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
*****Table.row.column
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
• C# NUnit
• Java JUnit
• JavaScript Mocha
• Python pytest
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 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-
• 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;
//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());
} else {
//if the message is not displayed , write FAIL in the excel sheet
cell.setCellValue("FAIL");
}
//wait for page to come back to registration page after close button is clicked
driver.manage().timeouts().implicitlyWait(2000, TimeUnit.SECONDS);
}
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;
.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;
driver.findElement(By.id(obj.getProperty("EmailTextBox"))).sendKeys("testguru
[email protected]");
driver.findElement(By.id(obj.getProperty("SignUpButton"))).click();
}
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.
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
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.
Google Chrome
System.setProperty("webdriver.chrome.driver", "/Users/neeraj.kumar/Desktop/chromedriver");
prefs.put("download.prompt_for_download", false);
options.setExperimentalOption("prefs", prefs);
Mozilla Firefox