0% found this document useful (0 votes)
26 views64 pages

Automation Related Topics

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

Automation Related Topics

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

Topics needed to prepare for interviews :

1. POM.xml (Maven)
2. Test NG
3. Maven
4. POM.xml
5. Zephyr
6. Collections
7. Oops concepts

Qns :

1. What are the different types of automation framework with which data’s can be passed to your
test cases.
2. How is your Automation Script connected to Jenkins , and how is it run
3. How is Automation test cases linked to JIRA test cases
4. How is the screenshots of the failures captured
5. How is the Final Reports of the Automation Job sent via Jenkins
6. Database testing via Automation
7. Can we run TestNG xml via a non maven project or only via maven project ?

Problem : Finding out which browser to be used.

Webdriver driver = NULL;


string browser ;

if(browser == "chrome") {
driver = new chromedriver;
}

else if (browser =="firefox"){


driver = new firefoxdriver;
}

Framework for Automation

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

1. Data Driven Automation Framework

2. Keyword Driven Automation Framework

3. Modular Automation Framework

4. Hybrid Automation Framework


TestNG (Section 2 – Section 12)

2. TestNG Tutorial: Annotations, Framework, Examples in Selenium

2.1 TestNG (NG stands for “Next Generation”)

TestNG, Junit both are automation framework. TestNG overcomes the disadvantages of JUnit and is
designed to make end-to-end testing easy.

Uses :

1. Proper reports can be made using Test NG (how many test cases failed , passed etc)
2. Specific test cases (methods) can be run.
3. Also supports running only failed test cases from previous run. Failed tc are stored in “testing-
failed.xml” in output folder which is then run specifically after fixing the issues.

Some of the Advantages of TestNG :

 Generate the report in a proper format including a number of test cases runs, the number of
test cases passed, the number of test cases failed, and the number of test cases skipped.

 Multiple test cases can be grouped more easily by converting them into testng.xml file. In which
you can make priorities which test case should be executed first.

 The same test case can be executed multiple times without loops just by using keyword called
'invocation count.'

 Using testng, you can execute multiple test cases on multiple browsers, i.e., cross browser
testing.

 The testing framework can be easily integrated with tools like Maven, Jenkins, etc.

 Annotations used in the testing are very easy to understand ex: @BeforeMethod,
@AfterMethod, @BeforeTest, @AfterTest

 WebDriver has no native mechanism for generating reports. TestNG can generate the report in a
readable format like the one shown below.
 TestNG simplifies the way the tests are coded. There is no more need for a static main method
in our tests. The sequence of actions is regulated by easy-to-understand annotations that do not
require methods to be static.


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

Advantages of TestNG over JUnit

There are three major advantages of TestNG over JUnit:

 Annotations are easier to understand

 Test cases can be grouped more easily

 Parallel execution of test cases are possible is possible

2.2 Annotations :

@Test(priority = 0, alwaysRun = true)

@BeforeTest - methods under this annotation will be executed prior to the first test case in the TestNG
file.
@AfterTest - methods under this annotation will be executed after all test cases in the TestNG file are
executed.

Order of execution Example :

@BeforeTest

@Test(priority = 1)

@Test(priority = 2)

@Test(priority = 3)

@AfterTest

--------------------------------------------------------------------------------------------

@BeforeMethod - methods under this annotation will be executed prior to each method in each test
case.

@AfterMethod - methods under this annotation will be executed after each method in each test case.

Order of execution example :

@BeforeMethod

@Test(priority = 1)

@AfterTest

@BeforeMethod

@Test(priority = 2)

@AfterTest

2.3 Summary of TestNG Annotations :

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

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

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

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

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

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

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

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

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

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

3. TestNG Groups: Include, Exclude with Example - Selenium


Tutorial

TestNG is a Testing framework that covers different types of test designs like unit, functional, end to
end, UI and integration test.

TestNG Xml’s are run through maven.

3.2 TestNG Groups with Example

@Test (groups = { "BVT", "Regression" })

Test NG Xml :

Include – This tell us the list of group names to be included in the run
Exclude – This tells us the list of group names that has to be excluded in the run

The below XML runs only the test cases in the “BVT” group

<groups>
<run>

<include name="BVT" />

</run>

</groups>

3.3 Suite, Test, Group, Class inside TestNG.XML

Suite : <suite> tag, holds a logical name. TestNG generates execution reports, information’s to these
TestNG reports are defined by the suite (Test NG report name)

Test : <test name="Guru 99 Smoke Test Demo">, this test name contains informations of the TestNG
generated reports like PASS, FAIL, UNEXECUTED, Time taken to execute, group informations etc.

Class : <class name="com.group.guru99.TC_Class1" />, where “com.group.guru99” is the the package


name (or project name) and TC_Class1 is the class name.

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

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

<suite name="Suite">

<test name="Guru 99 Smoke Test Demo">

<groups>

<run>

<include name="strong_ties" />

</run>

</groups>

<classes>

<class
name="com.group.guru99.TC_Class1" />

</classes>

</test>
</suite>

The above XML runs all the test cases inside the above mentioned class which has the group name as
mentioned above.

Also in the Test NG.xml we can specifically mention the list of method names that has to be run

Eg :

The below XML runs specially only the below 3 methods :


“method_name1, method_name2, method_name3”

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


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Guru 99 Smoke Test Demo">
<classes>
<class name="com.group.guru99.TC_Class1" />
<methods>
<include name =
“method_name1”><include>
<include name =
“method_name2”><include>
<include name =
“method_name3”><include>
</methods>
</classes>
</test>
</suite>

Maven & Jenkins Integration with Selenium: Complete


Tutorial
Maven – It is used for building a project in Jenkins

What is Maven?

Maven is a powerful project / build management tool, based on the concept of a POM (Project Object
Model) that includes project information and configuration information for Maven such as construction
directory, source directory, dependency, test source directory, Goals, plugins, etc.

Why Maven & Jenkins

Selenium WebDriver is great for browser automation. But, when using it for testing and building a test
framework, it feels underpowered. Integrating Maven with Selenium provides following benefits
Apache Maven provides support for managing the full lifecycle of a test project.
Maven is used to define project structure, dependencies, build, and test management.
Using pom.xml(Maven) you can configure dependencies needed for building testing and running code.
Maven automatically downloads the necessary files from the repository while building the project.

POM.XML

All the contents in the POM.XML will be build by the Maven, say all the dependencies available in the
POM.XML will be added to the build path at the time of build, with the help of Maven. Maven is used
to fetch the latest dependencies and will add those jar files to your build path. So that these can be
utilized by our code.

In Pom.xml add the Selenium, Maven, TestNG, Junit, Screenshot dependencies etc to pom.xml in the
<project> node:

<dependencies>
<dependency>
<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>3.8.1</version>

<scope>test</scope>

</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>

<artifactId>selenium-java</artifactId>

<version>2.45.0</version>

</dependency>
<dependency>
<groupId>org.testng</groupId>

<artifactId>testng</artifactId>

<version>6.8.8</version>

<scope>test</scope>
</dependency>
</dependencies>

Jenkins and Maven :

Using the Build a Maven Project option, Jenkins supports building and testing Maven projects.

So in eclipse, if you create a maven project, this can be easily added into Jenkins.

We configure POM.Xml, TestNG.XML, in the Jenkins for each Jobs.

4. TestNG @Test Priority in Selenium

If we don’t mention any priority, testng will execute the @Test methods based on alphabetical order of
their method names irrespective of their place of implementation in the code.

If multiple methods has same priority, then it will execute based on alphabetical order.
The test case with the lowest number will be run first. Followed by the 2 nd least number. This is how
priority works. It is case sensitive.

Test Case with Priority=0 will always be run first.

5. Parallel Execution in Selenium: Session Handling & TestNG


Dependency

Why do we need Session Handling?

When we run an automation script, it will be run in a browser. Each time a browser is opened it is
handled in a session. When we run multiple automation script, while another session or browser is
already running, the new script should not make the old session to stop. Hence session handling is
required

How to do session handling ?

In selenium by default, each time when we write the below piece of code, automatically a session is
given to this. A sessionid is already described as part of the chromedriver() implementation. Hence even
if we call the driver multiple times, each sessions will go on parallelly without getting interrupted.

Webdrive driver = new chromedriver();


Summary

 A new sessionID is created for a new instance of WebDriver.


 One session will bind with one particular browser.
 Using attribute thread and parallel, you run your scripts in parallel.
 You can use attribute dependency to set the order to test execution

<suite name="TestSuite" thread-count="3" parallel = “method”>

Tread-count ------------ Denotes the maximum number of session or browser that runs at a time

Parallel ------------------ Can take values “method”, “test”, “classes”. If

method -------------- it executes all the methods inside the mentioned class parallelly.

test---------------- it executes all the test cases metioned inside <test> tag in the testing.xml parallely.

Classes---------------- then it executes all the classes present inside a java class parallely.

8. TestNG: How to Run Multiple Test Suites in Selenium

Src is the project


Com.suite1 is the package
Flipkart is the class inside com.suite1

Similarly for goes for com.suite2(package) and snapdeal(class)


<suite thread-count="1" verbose="1" name="Gmail Suite" annotations="JDK"
parallel="tests">

<test name="flipkart">
<classes>
<class name="com.suite1.Flipkart"/>
</classes>
</test>

<test name="Myntra">
<classes>
<class name="com.suite2.SnapDeal"/>
</classes>
</test>
</suite>

In the above testing.xml, since the parallel = “tests”. All the test cases present inside the <test> tag in
the testNG.xml would be run parallel.

Note : Any method above which @Test is indiciated is called a test case

9. TestNG Listeners in Selenium: ITestListener & ITestResult


Example

Listener - Listener is defined as interface that modifies the default TestNG's behavior.

TestNG has multiple listeners. Nothing but multiple interfaces. Each of these interfaces will contain
multiple methods.
The main purpose of using Listener is to generate customised logs or customize TestNG reports in
Selenium Webdriver.

Below are the few TestNG listeners:

1. IAnnotationTransformer ,

2. IAnnotationTransformer2 ,

3. IConfigurable ,

4. IConfigurationListener ,

5. IExecutionListener,

6. IHookable ,

7. IInvokedMethodListener ,

8. IInvokedMethodListener2 ,

9. IMethodInterceptor ,

10. IReporter,

11. ISuiteListener,

12. ITestListener .

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

In this tutorial, we will implement the ITestListener.

ITestListener has following methods (These methods in ITestListener will be implemented after each
tests)

 OnStart- OnStart method is called when any Test starts.

 onTestSuccess- onTestSuccess method is called on the success of any Test.

 onTestFailure- onTestFailure method is called on the failure of any Test.

 onTestSkipped- onTestSkipped method is called on skipped of any Test.

 onTestFailedButWithinSuccessPercentage- method is called each time Test fails but is within


success percentage.
 onFinish- onFinish method is called after all Tests are executed.

How to Create ITestListener ?

Quick Steps :
1. Create a class and implement the required listener interface. This is a base Listener class
2. Create new classes and link the base listener class created in step1 to the required new classes
Or
Add the base listener class which we created in step 1 to the TestNG.XML. This will be applied to all the
methods in the test suite.

Detailed Steps :

extends is for when you're inheriting from a base class (i.e. extending its functionality).

implements is for when you're implementing an interface. (using an interface)

Step 1 : Create a Class and implement “ITestListener” interface. All empty methods are displayed below,
which are inherited from “ITestListener” package.

package Listener_Demo;

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

public class ListenerTest implements ITestListener

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

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

@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {

// TODO Auto-generated method stub

@Override
public void onTestFailure(ITestResult arg0) {

// TODO Auto-generated method stub

@Override
public void onTestSkipped(ITestResult arg0) {

// TODO Auto-generated method stub

@Override
public void onTestStart(ITestResult arg0) {

// TODO Auto-generated method stub

@Override
public void onTestSuccess(ITestResult arg0) {

// TODO Auto-generated method stub

}
}

Step 2 : Pass on whatever content you want in the above empty methods

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

public class ListenerTest implements ITestListener

@Override
public void onFinish(ITestContext arg0) {

driver.get("http://demo.guru99.com/V4/");
driver.findElement(By.name("uid")).sendKeys("mngr34926");
driver.findElement(By.name("password")).sendKeys("amUpenu");
driver.findElement(By.name("btnLogin")).click()

@Override
public void onStart(ITestContext arg0) {
System.out.println("This method to test fail");
Assert.assertTrue(false);

@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {

// TODO Auto-generated method stub

@Override
public void onTestFailure(ITestResult arg0) {

// TODO Auto-generated method stub

@Override
public void onTestSkipped(ITestResult arg0) {

// TODO Auto-generated method stub


}

@Override
public void onTestStart(ITestResult arg0) {

// TODO Auto-generated method stub

@Override
public void onTestSuccess(ITestResult arg0) {

// TODO Auto-generated method stub

How do I let TestNG know that I have such a listener which it should invoke when it is
executing my tests?
There are essentially two ways of adding up a listener to a particular class.

There are two ways by which we make a class as “Listener Class” :

1st Way : Adding @Listener(PackageName.ListenerClassName) on top of all the classes, this is a tedius
way. This is not the best approach as we have to modify all the classes one by one.

@Listeners(PackageName.ListenerClassName)
//eg : @Listeners(Listener_Demo.ListenerTest)
public class TestListener23545 {

2nd way (best approach) : Adding Listener in the TestNG.xml. This would implement listener

<suite name="Suite-Listeners" parallel="none">


<listeners>
<listener class-name="Listener_Demo.ListenerTest "></listener>
</listeners>
<test name="Batch-Listeners">
<classes>
<class name="automationFramework.TestListener" />
</classes>
</test>
</suite>
Summary:

 Listeners are required to generate logs or customize TestNG reports in Selenium Webdriver.
 There are many types of listeners and can be used as per requirements.
 Listeners are interfaces used in selenium web driver script
 Demonstrated the use of Listener in Selenium
 Implemented the Listeners for multiple classes

10. How to Execute Failed Test Cases in TestNG: Selenium


WebDriver

Run the TestNG.XML which we want to run. Inorder to create TestNG.XML, just choose the necessary
user created classes –> Right Click and choose TestNG -> Convert to TestNG -> Type the necessary
contents of the testng.xml and click finish.

Or else, while creating the class itself, we should have created a TestNG class.

“Test-output” folder – This folder contains the testNG.xml as well as the failedTestNG.xml as well.

Once the tests are run. Refesh the project and the package. Now a folder named “test-output” would be
displayed. Expand this “test-output” folder and “testng-failed.xml” would be displayed.

i.e,

test-output (folder) - testng-failed.xml (file)

Now right click and run this testng-failed.xml as TestNG suite.

Summary:

 TestNG is Automation Testing Framework which is inspired from the Junit and contains different
annotations.

 TestNG generates the reports in its standard report,which contains the following things:

o How many test cases are there ?

o How many test cases are passed ?

o How many test cases are failed ?


o How many test cases are skipped ?

 Multiple test cases can be grouped easily and executed them by converting test classes into
testing suite file.

 TestNG can be easily integrated with other third-party tools. It provides different features like
assigning the priority to the test cases, execution of same test case multiple times using
invocation count.

 If any of the test case fails while executing multiple test cases, you can execute that specific test
case separately.

 The static method "log" of Reporter class can be used to store logging information which is
present in org.testng.

Reporter.log(“the intended message”, true) - Parameter true is used to display the logs in the
console. Other wise, the logs will only be displayed in the testng reports.

11. TestNG Report Generation in Selenium WebDriver

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

 The TestNG will generate the default report.

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

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

Method-1 : emailable-report.html

1. Go to “test-output” folder and refresh it and then Click on option "emailable-report.html"

2. Click on option web browser

3. Contains just summarized information’s. Like number of passes and failures and unexecuted and
time taken.

Method-2 : index.html

1. contains indepth informations such as error, groups, time, reporter logs, testng XML
files.
2. Go to “test-output” folder and refresh it and then Right click on the index.html
3. Select option open with web browser option. It will display the result in the following
order.

Method 3 : Reporter Class

For implementing a reporting class, the class has to implement an org.testng.IReporter interface.

Report.log (“logger info” ); ---- this is similar to logger.info(“xtdsfds”)

“Report” is a class in “IReporter” interface. And “log” is a method inside “Report” class. This method
“log” is a static method, hence we are using it directly without creating any object.

org.testng.IReporter
public class Atest {
Public void Btest() {

Reporter.log(“dsgsd”);
}
}

Now run the TestNG.xml and open the emailable-report.html or index.html

The logs would also be present. The list of logs that got executed for each methods. This will be easy for
debugging.

12. Customize, PDF & Email TestNG Reports in Selenium


WebDriver

There can be two ways we can customize Basic TestNG report

 Using ITestListener Interface:

 Using IReporter Interface:

1. ITestListener

BASE LISTENER CLASS

package testNGReport.realTimeReport;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

public class RealGuru99TimeReport implements ITestListener{

@Override
public void onStart(ITestContext arg0) {

System.out.println("Start Of Execution(TEST)->"+arg0.getName());

@Override
public void onTestStart(ITestResult arg0) {

System.out.println("Test Started->"+arg0.getName());

:
:

REAL TEST CASE CLASS

@Listeners(RealGuru99TimeReport.class)
public class TestGuru99RealReport {

@Test
public void testRealReportOne(){
Assert.assertTrue(true);
}

@Test
public void testRealReportTwo(){
Assert.assertTrue(false);
}
2. IReporter

The coding part is bit tough, but is easier to implement only (So refer the https://www.guru99.com/pdf-
emails-and-screenshot-of-test-reports-in-selenium.html)

But for interviews this IReporter is not needed.

PDF and Email of Reports


Above ITestListener, IReporter will give you simple reports only. But in corporates, we need much higher
details .

1. Create Custom Report in PDF form (implemented inside base listener)

2. Take Screenshots ONLY on Errors. Link to screenshots in PDF (implement inside base listener)

3. Send Email of the PDF (implemented in a method which is executed after complete suite is
run)
Create a “JypersionListener” class, and implement the code for taking screenshot and attaching the link
to screenshot in the pdf inside the “OnTestFailure method” inside this Base listener class.

Note : JypersionListener is customer listener class which is used for taking screenshot and adding the
link to screenshot.

We can also use ITestListener instead of JypersionListener.

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

Now implement a method that has to be executed once all the test cases are run. That is @AfterSuite
method has to be created which contains the code for sending report PDF via email

//After complete execution send pdf report by email

@AfterSuite
public void tearDown(){

sendPDFReportByGMail("[email protected]", "password", "[email protected]",


"PDF Report", "");

:
:
:
: <<Content not over fully, so refer the above link for full content
}

Frameworks (Section 13 – Section tbd)

13.Page Object Model (POM) & Page Factory: Selenium WebDriver Tutorial

What is Page Object Model?

Page Object Model (POM) is a design pattern, popularly used in test automation that creates Object
Repository for web UI elements.

It helps make the code more readable, maintainable, and reusable.


What is Page Factory?

Page Factory is an inbuilt Page Object Model concept for Selenium WebDriver but it is very optimized.
@FindBy to find WebElement. PageFactory.initElements is needed to initialize all webelements on the
page object class.

We use Page Factory pattern to initialize web elements which are defined in Page Objects.

We should initialize page objects using initElements() method from PageFactory Class as below, Once we
call initElements() method, all elements will get initialized. PageFactory.initElements() static method
takes the driver instance of the given class and the class type, and returns a Page Object with its fields
fully initialized.

We create this as a constructor , so that whenever an object of this page object class is created, all the
webelements would be initialized.

Public class Homepage {


public HompePage(WebDriver driver) { //first method in each page object class
this.driver = driver;
PageFactory.initElements(driver, this);
}
}

AjaxElementLocatorFactory –

One of the key advantages of using Page Factory pattern is AjaxElementLocatorFactory Class.

It is working on lazy loading concept, i.e. a timeout for a WebElement will be assigned to the Object
page class with the help of AjaxElementLocatorFactory .

//it will wait for 100sec for visibility of element

AjaxElementLocatorFactory factory = new AjaxElementLocatorFactory(driver, 100);


PageFactory.initElements(factory, this);

(Note : Instead of this you can use any other types of wait. Explicity wait or implicit wait)

Summary

1. Page Object Model is an Object Repository design pattern in Selenium WebDriver.


2. POM creates our testing code maintainable, reusable.
3. Page Factory is an optimized way to create object repository in POM concept.
4. AjaxElementLocatorFactory is a lazy load concept in Page Factory pattern to identify
WebElements only when they are used in any operation.
14.Dataprovider & TestNG XML: Parameterization in Selenium(Example)

To pass multiple data to the application at runtime, we need to parameterize our test scripts.

This concept which we achieve by parameterization is called Data Driven Testing.

Type of Parameterization in TestNG :

There are two ways by which we can achieve parameterization in TestNG

1. With the help of Parameters annotation and TestNG XML file.

2. With the help of DataProvider annotation.

Parameters annotation with Testng.xml


TestNG.XMl

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


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" thread-count="3" >
<parameter name="author" value="Guru99" /> <! --parametzn at suite
level-->
<parameter name="searchKey" value="India" />
<test name="testGuru">
<parameter name="searchKey" value="UK" /> <! --parametzn at test level--
>
<classes>
<class name="parameters.ParameterWithTestNGXML">
</class>
</classes>
</test>
</suite>

If for a given test, parameters is available at both the suite level, and the test level in the testNG.xml,
then preference would be given to the parameters present at the test level in the testNG.xml

How to implement this Parameters in the test ?

The parameter variable name “author”, “searchkey” mentioned in the testNG.xml should be passed as
parameters for our method. The value for these variables would be fetched from the testNG.xml
@Test
@Parameters({"author","searchKey"})
public void testParameterWithXML( @Optional("Abc") String author,String
searchKey){

//content…
}

@Optional – If there is no value present for any variable in the testNG.xml, then the value mentioned in
the @Optional will be used for the variable for which no value is given in the xml.

Limitations :

1. We can’t use multiple different values for these parameters. Only 1 value mentioned in
the testNG.xml will be used throughout. For this we need to use “DataProviders”.

Parameters using Dataprovider

If we want to run a test case with multiple sets of data, then “Dataproviders” are used. A same test
case would be run with multiple sets of data.

@Parameters annotation is easy but to test with multiple sets of data we need to use Data Provider.

Data provider returns a two-dimensional JAVA object to the test method and the test method, will
invoke M times in a M*N type of object array. For example, if the DataProvider returns an array of 2*3
objects, the corresponding testcase will be invoked 2 times with 3 parameters each time.

@Test(dataProvider="SearchProvider")
public void testMethod(String author,String searchKey) {

//content
}
/**
* @return Object[][] where first column contains 'author'
* and second column contains 'searchKey'
*/

@DataProvider(name="SearchProvider")
public Object[][] getDataFromDataprovider(){
return new Object[][]
{
{ "Guru99", "India" },
{ "Krishna", "UK" },
{ "Bhupesh", "USA" }
};

Object array size is 3*2. The method will be run 3 times, with the values for the 2 parameters “author”
and “Search key” picked from each row of the dataprovider method.

Eg: 1st time when the above “testmethod” is run values for the 2 parameters mentioned in the
“testmethod” will be { "Guru99", "India" }.

2nd time when the above “testmethod” is run values for the 2 parameters mentioned in the
“testmethod” will be { "Krishna", "UK" }.

3rd time when the above “testmethod” is run values for the 2 parameters mentioned in the
“testmethod” will be { "Bhupesh", "USA" }

How to Invoke DataProvider from different class ?

If we want to call this data provider in different class, then make this data provider method as “Static”.
Then mention this class name where dataprovider object is implemented in other classes.

DataproviderClass.java (This is a common class containing the dataproviders and is a static method)

package parameters;

import org.testng.annotations.DataProvider;
public class DataproviderClass {
@DataProvider(name="SearchProvider")
public static Object[][] getDataFromDataprovider(){
return new Object[][] {
{ "Guru99", "India" },
{ "Krishna", "UK" },
{ "Bhupesh", "USA" }
};
}}

Now we want to implement above data providers in a different class for a different method or test case,
Public class workingTest {

@Test(dataProvider="SearchProvider",dataProviderClass=DataproviderClass.class
)
public void testMethod(String author,String searchKey) {

}
}

The same logic as mentioned in the above (data provider present inside the same class) will happen
now, and the 3 parameters present in the data provider will be passed on to our “testMethod” 3 times,
with different values.

Types of Parameters in Dataprovider

There are two type of parameters supported by DataProvider method.

14.1 Method – We can specify multiple set of values to be used as parameters for different
methods.

@Test(dataProvider="SearchProvider")
public void testMethodA(String author,String searchKey) {

If the method name is “testMethodA”, the first set of object parameters would be used. Or else 2nd set
of parameter values. We can use multiple else if’s as well.
14.2 ITestContext- It can use to create different parameters for test cases based on groups.

In the following code example

 We have 2 groups A & B

 Each test method is assigned to a group

 If value of group is A, a particular data set is returned (in below eg, 1st set of para would be run)

 If value of group is B, another data set is returned (in below eg, 2nd set of para would be run)

@Test(dataProvider="SearchProvider",groups="A")
public void testMethodA(String author,String searchKey) {

// 1st set of parameters groupArray would be used


}

@Test(dataProvider="SearchProvider",groups="B")
public void testMethodB(String searchKey){
// 2nd set of parameters groupArray would be used
}
TestNG.XMl

<test name="example1">
<groups>
<run>
<include name="A" />
</run>
</groups>
<classes>
<class
name="parameters.ParameterByITestContextInDataprovider" />
</classes>
</test>

<test name="example2">
<groups>
<run>
<include name="B" />
</run>
</groups>

<classes>
<class
name="parameters.ParameterByITestContextInDataprovider" />
</classes>
</test>
</suite>
15.Read & Write Data from Excel File in Selenium Webdriver: POI & JXL

To read or write an Excel,Apache provides a very famous library POI. This library is capable enough to
read and write both XLS and XLSX file format of Excel.

<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 and unzip it and add these all jars to the class
path of your project.

Following is a list of different Java Interfaces and classes in POI for reading XLS and XLSX file-

 Workbook: XSSFWorkbook and HSSFWorkbook classes implement this interface.

 XSSFWorkbook: Is a class representation of XLSX file.

 HSSFWorkbook: Is a class representation of XLS file.

 Sheet: XSSFSheet and HSSFSheet classes implement this interface.

 XSSFSheet: Is a class representing a sheet in an XLSX file.

 HSSFSheet: Is a class representing a sheet in an XLS file.

 Row: XSSFRow and HSSFRow classes implement this interface.

 XSSFRow: Is a class representing a row in the sheet of XLSX file.

 HSSFRow: Is a class representing a row in the sheet of XLS file.

 Cell: XSSFCell and HSSFCell classes implement this interface.

 XSSFCell: Is a class representing a cell in a row of XLSX file.

 HSSFCell: Is a class representing a cell in a row of XLS file.

File file = new File("filePath+"\\"+fileName");


FileInputStream inputStream = new FileInputStream(file);
//Assigning the interface required for our excel file (.XLS)
Workbook guru99Workbook = new HSSFWorkbook(inputStream);

//Read sheet inside the workbook by its name


Sheet guru99Sheet = guru99Workbook.getSheet(sheetName);

//Get the respective row which we want


Row row = guru99Sheet.getRow(i);

//Getting the cell value of the respective cell in that row and getting its value as string
row.getCell(j).getStringCellValue();

Qns for me :

1. Find out how login is implemented in swaftee..how browser is identified

The browser name is written inside POM.xml, inside <gridbrowser> or <browsername> tag. Then in our
test, we try to fetch the value stored for this browser tag from the POM.XML. And then try to create a
driver based on the value of this string.

2. Find the out we are importing from excel in xval project

<<Tbd>

Advance Webdriver Stuff!

16. Database Testing using Selenium: Step by Step Guide

Summary of Steps for Selenium Database Testing

Step 1) Make a connection to the Database using method.

DriverManager.getConnection(URL, "userid", "password")

Step 2) Create Query to the Database using the Statement Object.

Statement stmt = con.createStatement();

Step 3) Send the query to database using execute query and store the results in the ResultSet object.

ResultSet rs = stmt.executeQuery(select * from employee;);

Java provides lots of built-in methods to process the SQL Output using the ResultSet Object
Results from the executed query are stored in the ResultSet Object.

Java provides loads of advance methods to process the results. Few of the methods are listed below

Package htmldriver;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLConnector {
public static void main(String[] args) throws
ClassNotFoundException, SQLException {

//Connection URL Syntax:


"jdbc:mysql://ipaddress:portnumber/db_name"
String dbUrl = "jdbc:mysql://localhost:3036/emp";

//Database Username
String username = "root";

//Database Password
String password = "guru99";

//Query to Execute
String query = "select * from employee;";
//Load mysql jdbc driver
Class.forName("com.mysql.jdbc.Driver");

//Create Connection to DB
Connection con =
DriverManager.getConnection(dbUrl,username,password);

//Create Statement Object


Statement stmt = con.createStatement();

// Execute the SQL Query. Store results in ResultSet

ResultSet rs= stmt.executeQuery(query);

// While Loop to iterate through all data and print


results
while (rs.next()){
String myName = rs.getString(1);

String myAge = rs.getString(2);

System. out.println(myName+" "+myAge);


}
// closing DB Connection
con.close();
}
}

17.How to Take Screenshot in Selenium WebDriver

Note : Inorder to capture screenshots on exceptions throughout the script. We need to mention this
piece of code in the ITestListener class in the “OnTestFailure” method.

Steps to take screenshot (As given in swaftee):

Public void takeScreenShot(String filename) {


TakeScreenshot ts = new TakeScreenshotUtils(Boolean isDryRun, String basedirectorylocation, String currentdirectlylocation,
Boolean is CompareImages)
Ts.captureScreenshot(Driver, String filename);

Or

Capture Screenshot using Selenium WebDriver

Taking Screenshot in Selenium is a 3 Step process


Step 1) Convert web driver object to TakeScreenshot

TakesScreenshot scrShot =((TakesScreenshot)webdriver);

Step 2) Call getScreenshotAs method to create image file

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

Step 3) Copy file to Desired Location

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

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

public class Guru99TakeScreenshot {

@Test
public void testGuru99TakeScreenShot() throws Exception{
WebDriver driver ;
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
driver = new FirefoxDriver();

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

//Call take screenshot function


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

/**

* This function will take screenshot


* @param webdriver

* @param fileWithPath

* @throws Exception

*/

public static void takeSnapShot(WebDriver webdriver,String fileWithPath)


throws Exception{

//Convert web driver object to TakeScreenshot


TakesScreenshot scrShot =((TakesScreenshot)webdriver);

//Call getScreenshotAs method to create image file


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

//Move image file to new destination


File DestFile=new File(fileWithPath);

//Copy file at destination


FileUtils.copyFile(SrcFile, DestFile);

Capture Full Page Screenshot with AShot API

What is Ashot API?

Ashot is a third party utility by Yandex supported by Selenium WebDriver to capture the Screenshots.

Add the Ashot API dependencies in the POM.XML (maven)

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

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

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


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

 And now you are ready!!!

Steps for using Ashot Screenshot API :

Step 1) Create an Ashot object and call takeScreenshot() method if you just want the screenshot for the
screen size page.

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

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

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

18. Java Collections

https://www.javatpoint.com/collections-in-java (Study content) + geek for geeks


https://www.edureka.co/blog/interview-questions/java-collections-interview-questions/

Collection is a framework that contains interfaces and Classes which can be used to manipulate data in
the form of objects.
Hierarchy of Collection Framework
Core Interfaces in
Collections(collection,set,list,queue,dequeue,map)
The whole diagram is called as Collection Framework (framework is nothing but an architecture which
consists of interface and classes)
Collection(Root interface) Map

/ / \ \ |

/ / \ \ |

Set List Queue Dequeue SortedMap

SortedSet

Core Interfaces in Collections (Above diagram)

Note that this diagram only shows core interfaces.

Collection : Root interface with basic methods like add(),


remove(),

contains(), isEmpty(), addAll(), ... etc.

Set : Doesn't allow duplicates. Example implementations of Set

interface are HashSet (Hashing based) and TreeSet (balanced

BST based). Note that TreeSet implements SortedSet.

List : Can contain duplicates and elements are ordered. Example

implementations are LinkedList (linked list based) and

ArrayList (dynamic array based)

Queue : Typically order elements in FIFO order except exceptions

like PriorityQueue.
Deque : Elements can be inserted and removed at both ends. Allows

both LIFO and FIFO.

Map : Contains Key value pairs. Doesn't allow duplicates. Example

implementation are HashMap and TreeMap.

TreeMap implements SortedMap.

The difference between Set and Map interface is that in Set we

have only keys, whereas in Map, we have key, value pairs.

Advantages of using Collections :


Earlier each datatype used to have its own methods for manipulating data (Eg: add,remove, empty etc).
It was difficult to memorise each of these methods for each data types(linkedlist,arraylist etc). Hence
they came up with a concept of collection, where all the classes under this framework has common data
manipulation methods.
19.Static methods available in Collections class and Collection interface in java
https://www.journaldev.com/16635/collections-class-java-util-collections
https://www.journaldev.com/16770/java-arrays-java-util-arrays
https://www.journaldev.com/11444/java-list
https://www.journaldev.com/11641/java-map
https://www.journaldev.com/13242/java-set
https://www.journaldev.com/1260/collections-in-java-tutorial (Start here)
--------------------------------------
https://www.edureka.co/blog/java-string-pool/
https://www.edureka.co/blog/java-arraylist/
-------------------------------------
https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html

Comparator : It is an interface, using which we can definite a class which consists of the ways in which
we want to sort the elements in a list or set. These are custom defined class which consists of the way in
which the sorting has to be done. In other words these are used for custom ordering or custom sorting
of elements.
Enumerator : these are just used to iterate over collections. has 2 methods hasMoreElements(),
nextElement().Enumerator does not have remove().Enumeration interface acts as a read only interface,
one can not do any modifications to Collection while traversing the elements of the Collection.
Enumeration is a legacy interface which is used for traversing Vector, Hashtable.

Iterator : these are used to iterate over elements in a collections. has 3 methods hasNext(), next(),
remove(). Using Iterator we can do modifications to the collections as well. Iterator is not a legacy
interface. Iterator can be used for the traversal of HashMap, LinkedList, ArrayList, HashSet, TreeMap,
TreeSet .

20. What is enum ? <<Study urself>>

20 . Selenium interview questions :


 Verify – Soft assert,
Assert – Hard assert

 4 parameters needed for running selenium – Host, port, browser, url


 ClickAt(locator, cordinatesString) – clicks on the locator + the coordinates
Click(locator) – just clicks on the locator

 SetSpeed(milliseconds) – Waits for amount of time mentioned in the parameter for executing
each line of command
Sleep(milliseconds) – Thread.sleep functionality.
 Submit() or click() – both performs same action
 findelement() – finds the first matching element in the page
findelements() – finds all the elements matching the locator and stores them in list
 Datadriven framework – 1. Storing the values in external files like excel and then reading them
and storing them as variables and using these variables in our test methods. Data’s are not
stored in test methods. Only the test case steps or logic resides inside the test method.
Also Passing multiple test data’s for a same method. storing the test data’s in a
separate file. Either xml (testng xml) or excel

 Selenium grid - Selenium Grid sent the tests to the hub. These tests are redirected to Selenium
Webdriver, which launch the browser and run the test. With entire test suite, it allows for
running tests in parallel.

How to get element background colour or element text colour of an element in selenium ?

 getCssValue("background-color") – gets the background colour of an element


getCssValue("color"); - gets the text colour of an element

 how you can switch between frames?

Search for “iframe-tags”. In page source to find if there are iframes inside a page

driver.switchTo().frame() ---- syntax for switching an iframe

It can be implemented in 3 ways :

switchTo.frame(frameindexnumber)
switchTo.frame(frame name or id)
switchTo.frame(webelement)

Finding total number of iframes. Creating a list which stores all the webelements with tag name
“iframeResult”.

List<WebElement> iframeElements = driver.findElements(By.tagName("iframeResult"));


System.out.println("Total number of iframes are " + iframeElements.size());

//Switching back to main frame


driver.switchTo().defaultContent();

 Some different exceptions in selenium webdriver :

WebDriverException - Exception comes when a code is unable to initialize WebDriver.


NoAlertPresentException - If a user tries to handle an alert box but the alert is not present.
NoSuchWindowException - This is thrown when WebDriver tries to switch to an invalid window.
if the window handle doesn’t exist or is not available to switch.
NoSuchElementException - This exception is due to accessing an element which is not available
on the page.
ElementNotVisibleException - If selenium tries to find an element but the element is not visible
within the page
ElementNotSelectableException - ElementNotSelectableException indicates that the web
element is present in the web page but cannot be selected.
TimeoutException
NoSuchAttributeException - While trying to get attribute value but the attribute is not available
in DOM.
NoSuchFrameException - When WebDriver is trying to switch to an invalid frame,
NoSuchFrameException under NotFoundException class is thrown.

 Alerts are nothing but small popups/alert boxes appearing on the same tab or window.

driver.switchTo().alert().dismiss() ---- This method is used to click on the 'Cancel' button of the
alert.

driver.switchTo().alert().accept(); ----- This method is used to click on the 'Ok' button of the
alert.

driver.switchTo().alert().getText(); ---- This method is used to capture the alert message.

driver.switchTo().alert().sendKeys("Text"); ---- This method is used to send some data to the


alert box.

 Doublicking in selenium : Actions class has a method doubleClick

Actions act = new Actions (driver);


act.doubleClick(webelement);

 getwindowhandles(): It is used to get the address of all the open browser and its return type is
Set<String>

getwindowhandle(): It is used to get the address of the current browser where the control is
and return type is string

 Different types of locators are

By.id()
By.name()
By.tagName()
By.className()
By.linkText()
By.partialLinkText()
By.xpath
By.cssSelector()
 How will you handle working with multiple windows in Selenium ?

selectWindow() – This is used to switch between windows. This command uses the title of
Windows to identify which window to switch to.

 sendkeys() - To enter values onto text boxes


 isElementPresent(String locator) – returns Boolean results. This is used to identify an object is
present or not using Selenium

 Mention why do you need Session Handling while working with Selenium?

So that multiple browsers would be opened at a same time and each different automated operations
would be performed on each of these browsers without interfering between one another. Also it is
possible to run a new script which will invoke browser even before the old script is over .Basically
multiple browsers run on a same machine and they should not disturb or interfere with one another. So
to avoid such situation you need Session Handling.

Xpath : full form is XML path

Synatax : Xpath=//tagname[@attribute='value']

Absolete xpath – long and big and starts from the starting node of the xml.
Relative Xpath – starts from the middle or anywhere in the page.

/ - single slash means that it is starting the xpath from the root node or the very first node of the page
that is available.

// - double slash means searching anywhere in the page and starting from the specified element.

XPath axes – Are methods to find complex or dynamic elements. Few commonly used axes methods in
selenium webdriver are child, parent, ancestor, sibling, preceding, self, etc.

How to insert or add or concatenate a string in the xpath that we are creating ?

String.format method is used to give formatted string. The first argument takes in the string containing
the format specifier. The second argument replaces the value in place of the format specifier.

Format specifier : %d – integer value , %s – string value

Example for String.format method :

String sf1=String.format("name is %s", "sonoo");


System.out.println(sf1);

Output :
name is sonoo
Method 1 :

String element =".//*[@id='button-%s']";

public String interpolation(String xpath, String variable) {


return String.format(xpath, variables);
}

driver.findElement(By.xpath(interpolation(element, "one"));

Method 2 (Easy):

Syntax : String.format(xpath containing %s, variable that we want to replace for %s)

driver.findElement(By.xpath(String.format("//*[@id='button-%s']", variable_replacementValue)));

1. Contains() - contain function inside Xpath has an ability to find the element with partial
text.

Syntax : Contains(attribute, partial value)

Xpath=//*[contains(@id,'sub')]
Xpath=//*[contains(text(),'here')]

2. Using OR & AND – AND, OR operators can be used inside Xpath.

Xpath=//*[@type='submit' or @name='btnReset'] – finds elements with atleast


one condion true.

Xpath=//input[@type='submit' and @name='btnLogin'] – find elements with both


the condition true.

3. Starts-with function – Finds the elements stating with the given value

Xpath=//label[starts-with(@id,'message')]

4. Text() – Used inside xpath to find elements with exact Text match.

 Xpath=//td[text()='UserID']

20.1
driver.quit () – Used to close all the browser session along with the browser window, popup, tabs
associated with it.

Driver.close() – Closes only the current browser window/tab/popup which is in focus.

20.2

boolean isElementPresent(webelement) – Checks whether this webelement is present anywhere on


the page

boolean isVisible(webelement) – Checks whether this webelement is visible to the user on the UI. Some
elements might be hidden, Visiblity condition makes sure that the element is not hidden on the UI.

20.3 AJAX calls – Asynchronous Javascript and XML.

These calls are sent inorder to not load the whole page whenever we get any response from the server
for the desired browser action. Eg : We submit a form, now this request will be sent from browser to
server. Server’s response would be sent back to the browser. Now if the browser doesn’t load the whole
page inorder to show us the response for the Submit button. Then it is called as AJAX Calls.

Any actions that happens on the page without actually reloading the page, in these cases AJAX calls
were made from the browser by the application.

Waits times are difficult for AJAX calls. Cause we don’t know the load time.

20.4 Different types of Waits :


Thread.Sleep (time) – Just puts on hold for the time specified in the parameter irrespective of any
checks.

Implicit wait – Waits for the element to be present on the page until the specified time or else throws
exception if the time limit is reached. If the element is found to be present much before the maximum
time specified, then it will move to next step.

Disadvantage : If we declare this implicit wait, then for our full script this will happen. i.e for each line.

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

Explicit Wait :

Advantage over Implicit wait : This action can be performed to our desired piece of code. i.e Only for
the elements that we want.

Webdriver wait : Waits for the element until a specific condition is met. Or else waits for max time given
by the user before throwing exception. Polling is done after every 0.5 secs.

Polling is nothing but sending out the request to DOM (page source) to check whether the element
meets the mentioned condition.

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);

WebDriverWait wait = new WebDriverWait(driver, 5);


wait.until(ExpectedConditions.visibilityOfElementLocated(webelement));

The following are the Expected Conditions that can be used in 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()

FleuntWait – It is same as WebdriverWait, but the only difference is here we can mentioned even the
polling frequency. I.e the frequency at which the condition check is done.

Wait wait = new FluentWait(WebDriver reference)


.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);

WebElement foo=wait.until(new Function<WebDriver, WebElement>() {


public WebElement applyy(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});

20.5 What is the difference between a truncate, drop and delete (SQL Question)

Delete – Delete few rows or full rows using WHERE clause. These changes can be rolled back.
(recovered)

DELETE FROM emp WHERE job = 'CLERK'

Truncate - removes all rows from a table. This operation cannot be rolled back

TRUNCATE TABLE emp;

Drop - removes a table from the database. All the tables' rows, indexes and privileges will also be removed.
This operation cannot be rolled back.
DROP TABLE emp

ROLLBACK - undo changes made to the database. Any command which was executed, will be undone.

INSERT INTO tab1 VALUES ('val1', 'val2', 'val3');


ROLLBACK;

Partial RollBack –

One can specify savepoints to mark a point in a transaction to rollback to. In the below example the Update
command which we performed is rolled back

DELETE FROM emp WHERE empno = 123;


SAVEPOINT x;
UPDATE emp SET sal = sal * 1.1;
ROLLBACK TO SAVEPOINT x;
COMMIT;

COMMIT - make changes permanent

Savepoint – It is a marker or point in an transaction to which you can later roll back.

DELETE FROM dept WHERE deptno = 123;


SAVEPOINT step1;

INSERT INTO dept VALUES (123, 'Editors', Oracle FAQ');


SAVEPOINT step2;

ROLLBACK TO SAVEPOINT step1;


COMMIT;

20.6 Types of Joins

(Inner)Join – Displays matching record in both tables


Left(outer) join – Displays all records from left table and matching record from right table
Right(outer) join – Displays all records from right table and matching record from left table
Full join – Displays all records from both table
20.7 Difference between XPath and CSS selectors?

Xpath CSS
full form - XML path Cascade Style Sheet
Both forward and backward traversal is supported Only forward traversal is supported
when compared to CSS, it is slower to find elements faster to find the element
Complex to read Easy to read

20.8 What is a constructor, constructor chaining?

Constructor – It is a piece of code that is executed first as soon as the object of that class is created. The
constructor name has the same name to that of the Class name, but there are no datatype for
constructors.

Constructor Chaining – Calling one Constructor within another constructors with respect to current
object.

Withing Same class – it can be done using keyword this() . In the code, wherever this() is used.

TIPS FOR UNDERSTANDING EASILY : Consider it is similar to constructorName(). i.e instead of using the
“Constructor” name once again, we are using this(). But functionality wise both are same. When this() is
used, imagine replacing it with current class name. When super() is used, consider replacing it with Base
class name.

From base class - by using super() keyword to call constructor from the base class.

Order of execution : While traversing in the constructor chaining, the piece of code within the last
traversed constructor would be executed first followed by the next topmost constructor. Like wise.

Rules for Constructor chaining : 1. Atleast one constructor should be without this() keyword. 2. First line
of the constructor should contain this().

Why do we use constructor chaining ?

Instead of writing all the piece of code within a same constructor, we are storing each code in different
constructors. One of the example is using super(driver) is in automation for each page object class. We
call super(Driver) so that the driver that is returned from the base class is called.

/ Java program to illustrate Constructor Chaining


// within same class Using this() keyword
// and changing order of constructors
class Temp
{
Temp() // default constructor 1
{
System.out.println("default");
}
Temp(int x) // parameterized constructor 2
{
this(); // code is taken to default constructor
System.out.println(x);
}

Temp(int x, int y) // parameterized constructor 3


{

this(5); // code is taken to parameterized constructor 2


System.out.println(x * y);
}

public static void main(String args[])


{
new Temp(8, 10); //code is taken to parameterized constructor 3
}
}
Output:
default
5
80

20.9 Init block – these are nothing but the piece of code which is written within open “{“ and closed
parenthesis “}” within a class. On creating an object all the code within this init block is executed first,
then only even the constructor is called. Similar to Constructor but this is executed first before even
calling the constructor.

class Temp
{
// block to be executed before any constructor.
{
System.out.println("init block");
}

20.10 Multiple inheritance not supported in Java because it causes confusion if a method with same
name is present in more than 1 classes.

Whereas using interface, Java supports multiple inheritance. In this we use the keyword Super() to
specify which method to be called.

Syntax : InterfaceName.Super.MethodName();

20.11 : Object Class – SuperClass of all classes in Java

java.lang.Object

Some methods in Object class are wait(), toString(), equals(),


20.12 : Difference between CompareTo(), equals(), Compare().

Compareto() – Compares the Unicode value of the two strings and gives the difference in integer
format. 0 means both are same strings.

Compare – compares the ASCII value of the two strings and gives the difference in integer format. 0
means both are same strings.

equals() – compares whether the content of 2 objects are equal or not even if both the objects are
different. Returns true or false.

== (equalTo) – does the same job of equals(), but only if both the objects are same and of same
datatype as well.

equalsIgnoreCase() – ignores cases

20.13 How to get parent window id and child window id. ?

Steps :

1. Get the window id of current window (parent window) using getWindowHandle and
store it in a variable
2. Get all the window id using getWindowHandles and store them in a set or list.
3. Now remove our parent windowhandle from the above set. Now we will be left with only
the child window id’s
4. Iterate over to the desired child id and then switch back to parent window handle
whenever required.

String parent = driver.getWindowHandle();


Set<String> windows = driver.getWindowHandles()
windows.remove(parent);
Iterator<String> it = windows.iterator();
String child=null; //This is for referencing specific child window
while(it.hasNext()){
child=(String)it.next();
driver.switchTo.window(child);
//perform action that you want to perform on child window
}
driver.switchTo.window(parent); // switch back to parent window

20.14 Typecasting – The process of converting value of one datatype to another datatype.

Example : Converting double into an int :


This can be done in 2 ways :
1st way : Widening Type Casting (Java automatically converts based on the variable’s datatype

double num = 10.99;


int abc = num;

Now abc will hold value 10.

2nd way (best way): Narrowing Type Casting – We manually change from one datatype to another by
putting the datatype which we needed within parenthesis.

int abc = (int)Math.log10(150); //output Converted to integer


String pqr = (String)it.next(); //output Converted to String

Math.Log function returns doubt data type. Now we have converted that double to int using
typecasting.

20.15 setProperty in Selenium

setProperty is use for setting the path of the driver of the respective browser that we want to run the
scripts.
Since the browsers doesn’t have an inbuilt server to run the automation code, we have to mention the
driver and its path manually before starting any automation script.

Syntax : System.setProperty(“Browserdriver Name”, “BrowserDriver


location”)

1st parameter takes in the name of the system property.


2nd parameter takes in the value of the system propery.

Example :

public void launchChrome()


{

System.setProperty("webdriver.chrome.driver","C:\\Utility\\BrowserDrivers\\
chromedriver.exe");

Webdriver driver=new ChromeDriver();


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

20.16 Action Class and its importance

Actions class is a built-in ability to handle various types of keyboard and mouse events.
Used for accessing the drop-down box, double click, right click, click enter button, drag and drop,
keyboard short cut actions etc
Note : Right click is also called as “context click” in selenium

Example 1 :
Actions action = new Actions(driver);
action.moveToElement(element).perform();
action.doubleclick().perform();

Example 2 :
Actions action = new Actions(driver);
action.moveToElement(element).doubleclick().build().perform();

Example 3 :
Actions builder = new Actions(driver);
builder.clickAndHold(element1).clickAndHold(element2).click().build().perform
();

Example 4 : Right click


Actions action = new Actions(driver);
action.contextClick(element).perform();

Note : Usually for a single action we can just use either build() or perform(). Not necessary to use both.
Even using both is not an issue.

But when we are doing a multiple operations to be performed like, then we need to use build() and
perform() for compiling and executing.

build().perform() ---> this method is used to compile(build) and execute(perform) the action class

Difference between Webelement.click() and Action.click() ?

Please note that the normal webelemt class supports simple methods like click(), submit(), sendkeys().
Those doesn’t come under action class, hence you need not use build, perform or action class object for
those.

To click enter button in selenium :

import org.openqa.selenium.Keys

WebElement.sendKeys(Keys.RETURN);

Or

driver.findElement(By.id("Value")).sendKeys(Keys.ENTER);
20.17 Can we run our automation script even without installing chrome browser in our system ?

Yes we can run automation scripts even without installing chrome browser in UI. We can run the
automation script using headless browser. This is useful when we have to run an automation script in a
server, where browser install options are not there.

Browsers supporting headless browsers :


Headless Chrome
Headless firefox

Advantages of running in headless browser:

1. Saves time and is faster since we really can’t see this browser on the screen and it only runs on
the background.
2. You could use the installed browser for some other testing purpose.

Syntax :

System.setProperty("webdriver.chrome.driver","ChromeDriverPath");
ChromeOptions options = new ChromeOptions();
options.addArguments("headless");
options.addArguments("window-size=1200x600");

WebDriver driver = new ChromeDriver(options);


driver.get("https://contentstack.built.io");

20.18 What is the method to disable cookies via selenium

Using ChromeOptions class and setExperimentalOptions method

Map prefs = new HashMap();


prefs.put("profile.default_content_settings.cookies", 2); //2 denotes
disabled
ChromeOptions options = new ChromeOptions();
options.setExperimentalOptions("prefs", prefs);
driver = new ChromeDriver(options);

In selenium we can interact with cookies using following commands :

driver.manage().getCookies(); // Return The List of all Cookies


driver.manage().getCookieNamed(arg0); //Return specific cookie according to
name
driver.manage().addCookie(arg0); //Create and add the cookie
driver.manage().deleteCookieNamed(arg0); // Delete specific cookie according
Name
driver.manage().deleteAllCookies(); // Delete all cookies
20.19 Webelement methods

1. SendKeys() – Used to enter text into the Text Fields and Password Fields
Syntax : Webelement.sendkeys(“xyz”);

2. clear() – Used to delete all values in a input box


Syntax : Webelement.clear();

3. click() – Used to click a button or a textbox or any webelement


Syntax : Webelement.click();

4. Submit() – Used to submit the entire form to the server. It is supported only if the webelement
is a button. Usually for a button, both submit() and click() behaves the same.

Syntax : webelement.submit();

20.20 How to check if an element is present, enabled, visible, find text in selenium webdriver

1. To check Element Present:

if(driver.findElements(By.xpath("value")).size() != 0){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}
Or

if(driver.findElement(By.xpath("value"))!= null){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}

2. To check Visible:

if( driver.findElement(By.cssSelector("a > font")).isDisplayed()){


System.out.println("Element is Visible");
}else{
System.out.println("Element is InVisible");
}

3. To check Enable:

if(driver.findElement(By.cssSelector("a > font")).isEnabled(){


System.out.println("Element is Enable");
}else{
System.out.println("Element is Disabled");
}

4. To check text present


if(driver.getPageSource().contains("Text to check")){
System.out.println("Text is present");
}else{
System.out.println("Text is absent");
}

20.21 selecting values from “select” dropdowns - Important

Using “Select” class we can pass the values that we want for our dropdown. The dropdown tag should
be “Select” inorder to do this.

List of methods supported by “Select” class are :


selectByVisibleText(String text) – selects the option from the dropdown matching the string we are
passing.
deselectByVisibleText(String text) - deselects the option that we are passing
selectByValue(String value) – selects the option from the dropdown having the respective “value”
attribute.
deselectByValue(String value) – Deselects the option from the dropdown having the respective “value”
attribute.
selectByIndex(int index) – selects the option from the dropdown based on the index value
deselectByIndex(int index) – deselects the option from the dropdown based on the index value
isMultiple() - Returns TRUE if the drop-down element allows multiple selections at a time; FALSE if
otherwise.
deselectAll() - Clears all selected entries. Only applicable for multi select drodowns

Example 1 : selectByVisibleText(String text)

WebElement element=driver.findElement(By.id("year")); //location of dropdown


Select select = new Select(element);
select.selectByVisibleText("2015");

Example 2 : Selecting multiple elements from the dropdown

WebElement element=driver.findElement(By.id("year")); //location of dropdown


Select select = new Select(element);
select.selectByVisibleText("2015");
select.selectByIndex(1);
select.selectByValue(“345”);

20.22 How to get the text from a page and store it in a file.

getText() – This method is used to get the text value of the webelement
File – File class is used for creating file objects. Cause only file objects are supported in FileUtils class
methods.
FileUtils.writeStringTofile – is used to store the string to the destination file.
String output = driver.findElement(By.id("abc")).getText();
File DestFile= new File("extractedFilePath"); //file is a class used for
creating file objects
FileUtils.writeStringToFile(DestFile, output);

20.23 FileUtils class in selenium – It is a Static Class

Methods available in FileUtils class :

Syntax : FileUtils.writeStringToFile(File file, String output):

contentEquals(File file1, File file2): It compares the contents of 2 File objects, and returns whether they
are the same or not.

write(File file, CharSequence data): Writes a CharSequence in a file, using the specified enoding.

writeLines(File file, Collection<?> lines): Writes the collection of lines to a File.

writeStringToFile(File file, String output): Writes the string into the specified file.

copyFile(File sourcefile, File destinationfile) : copies the content of one file to another file, it overrides
the content in the destination file.

20.24 How to count the number of elements (say links, or anyother element) using selenium

Steps :
1. Find all the elements using findelements method and store them in a Webelement List.
2. Find the size of the webelement list, it will give us the total count of the elements.

Example 1 :
List<WebElement> xpath =
driver.findElements(By.xpath("//div[@id='billingProfiles']/div[@class='cardCon
tainer']"));

int xpathCount = xpath.size();


System.out.println("Total xpath: " + xpathCount);

Example 2:Find the total number of links in a page.


List<WebElement> totalLinks = driver.findElements(By.tagName("a"));
int totalLinkSize = totalLinks.size();
System.out.println("Total Links by Way1 : " + totalLinkSize);

20.25 Clicking back button/ forward button/ refreshing a webpage using Selenium

driver.navigate().back(); - Go back to Home Page


driver.navigate().forward(); // Go forward to Registration page
driver.navigate().to("https://www.testandquiz.com/selenium/testing.html"); //Navigate to the desi
red URL
driver.navigate().refresh(); // Refresh browser

Difference between driver.get() and driver.nagivate.to() ?

driver.get() : It's used to go to the particular website , But it doesn't maintain the browser History and
cookies so , we can't use forward and backward button , if we click on that , page will not get schedule

driver.navigate().to() : it's used to go to the particular website , but it maintains the browser history and
cookies, so we can use forward and backward button to navigate between the pages during the coding
of Testcase

20.26 Asserting the title of the page

String titleofthepage = driver.getTitle(); //gettitle method is used to get the title of the webpage
And using asserting we can assert whether the value of the title is correct as we expected or not

assertArrayEquals(expectedArray, resultArray);
assertEquals(String Actual, String expected);
assertNotEquals(String Actual, String expected)
assertTrue(Boolean abc) – the assertion is successful if the condition returns TRUE
assertFalse(Boolean abc) – the assertion is successful if the condition returns FALSE
assertNull(variable or object): the assertion is successful if the expected output is null.
assertNotNull(variable or object) : the assertion is successful if the expected output is not null.

Softassert syntax :

SoftAssert softassert = new SoftAssert();


softassert.assertequals();
softassert.assertTrue();
:
:
:
softassert.assertAll();

20.27 what are the immutable classes in java

Immutable class means that once an object is created, we cannot change its content. In Java, all
the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable by default.
Any variable created with the above classes, its content cannot be modified. Once initialized its value
cannot be modified.

Final – this keyword is used to make the classes immutable.

20.28 selenium webdriver hierarchy

Cookies :

Introduction to Selenium Cookies


A cookie is a small piece of data that is sent from a website and stored on the user’s computer. Cookies
are also used to recognize the user if they return to a website, and load the previously stored information.
Mostly, cookies store the user’s identity and track the user’s journey through the pages of the website.
WebDriver API provides a way to interact with cookies with built-in methods.
Now, let’s have a look at the various selenium commands for cookies.

Selenium commands for Cookies


The commands below are used to get, add, and delete all cookies present in a browser:

 Get Cookie: Gets the cookies for the current domain.

driver.manage().getCookies(); // Returns the List of all Cookies

driver.manage().getCookieNamed(arg0); //Returns the specific cookie according


to name
 Add Cookie: Adds a specific cookie into cookies. If the cookie’s domain name is blank, it is assumed
that the cookie is meant for the domain of the current document.

driver.manage().addCookie(arg0); //Creates and adds the cookie

 Delete Cookie: Deletes the cookies for the current domain.

driver.manage().deleteCookie(arg0); // Deletes the specific cookie

driver.manage().deleteCookieNamed(arg0); // Deletes the specific cookie


according to the Name

driver.manage().deleteAllCookies(); // Deletes all the cookies

Why is Cookie Handling necessary?


When testing a web application using selenium webdriver, testers can create, update or delete a cookie.
For example, when automating an online food delivery application, the tester needs to automate various
user scenarios like placing an order, viewing cart, paying, receiving the order confirmation, etc. If cookies
are not stored, the user needs to log in every time before executing the test scenarios listed above. That
increases coding effort and execution time.

System.setproperty

We need not write system.setproperty at the start of out automation script each time, provided we
added this location in the “Environment variable” settings in the “System” app in the windows.

Open “systems” -> Advanced system settings -> environment variables ->Edit path and add this path as
well where the driver should be present.

System.setProperty("webdriver.chrome.driver", ".\\Driver\\chromedriver.exe");

Desired Capabilities in Selenium WebDriver

https://www.guru99.com/desired-capabilities-selenium.html

The desired capability is a series of key/value pairs that stores the browser properties like browsername,
browser version, the path of the browser driver in the system, etc. to determine the behaviour of the
browser at run time.

Selenium : It is a framework, which is used for Automation testing.

Selenium consists of : selenium ide , selenium webdriver (webdriver + selenium rc), selenium grid.

Selenium ide : uses the language called selenese. Build in feature of Firefox, where we record and run a
scenario. Not suitable for large code base, and changing data’s
Selenium rc : We can write the code in any complex language (java, python etc). But it doesn’t directly
interact with browser. It sends the code to Selenium RC server. Server then sends to Browser in the form
of Javascript. As selenium rc is not directly communicating with browser, it is not so fast. Also due to
javascript injection there can be some issues. Eg : sometimes if a field is not editable, but with javascript
that would still pass values without errors.

Webdriver : Directly communicates with the browser application in the Operation system. Supports
working in various operating systems and browsers. It is faster.

Selenium grid : It is a component of selenium rc which is used to run multiple test cases parallely in
various browsers as well.

20.29 Read data from Properties file using Java Selenium

datafile.properties file (Contents)


URL=http://gmail.com
Username=testuser
Password=password123

Selenium Code :
File file = new File("D:/Dev/ReadData/src/datafile.properties")
FileInputStream fileInput = new FileInputStream(file);
Properties prop = new Properties();
prop.load(fileInput);
driver.get(prop.getProperty("URL"));
System.out.println("URL ::" + prop.getProperty("URL"));
System.out.println("User name::" +prop.getProperty("username"));
System.out.println("Password::" +prop.getProperty("password"));

Output :
URL ::http://gmail.com
User name::testuser
Password::password123

We can use setProperty() method to update an existed key-value pair or add a new key-value pair.
props.setProperty("name", "NewAppName"); // Create a new value or update an old value

If you want to remove a key-value pair, you can use remove() method.
Props.remove("keyname");

You might also like