Professional Documents
Culture Documents
Automation testing uses the specialized tools to automate the execution of manually designed
test cases without any human intervention. Automation testing tools can access the test data,
controls the execution of tests and compares the actual result against the expected result.
Consequently, generating detailed test reports of the system under test.
Automation testing is the best way to increase the effectiveness, efficiency and coverage of
software testing.
Selenium:
RC- In this, Http proxy server was used.Scripts designed first communicates with proxy server and then
actions were performed in Web applications.If In case user has multiple testcases, so the execution time
will be very slow . Hence this is
Webdriver: no proxy http, scripts directly talks with the web based application
Selenium IDE: plugin for firefox , used for record & playback feature
Grid: its used for parallel execution of automated scripts across different platforms remotely on different
browsers simultaneously.
Limitations of selenium:
3. It cant read & write data in excel sheets by default-à Apache POI integration required
Browser Drivers:
We know that Selenium runs in multiple browsers. Browser drivers help to run selenium scripts
on the browser. They act as a bridge that interprets the selenium commands to execute it in the
SELENIUM & TESTNG NOTES
browser. There are separate browser drivers for each browser, for example, ChromeDriver,
EdgeDriver, FirefoxDriver, InternetExplorerDriver, OperaDriver, SafariDriver, etc.
Interface Webdriver
{
SELENIUM & TESTNG NOTES
Selenium Locators:
Selenium identifies the elements on a Web Page using the Locators. These locators are present
on the source page(HTML code) of a web page. In an HTML source code of a web page, all the
elements are defined with the help of tags and attributes.
Name,ID, classname,Css Selector, Xpath, LinkText, partial link text
method returns the WebElement interface reference. Let’s try an example for each of the
locators.
Line no: 16:Here, findElement is a method in the WebDriver interface that returns the
WebElement reference. By is a class in Selenium, which has the mechanism to locate
elements. And, it has static methods in it. One of them is the id(java.lang.String id).
Xpath Locator:
Xpath represents the address of a HTML webelement on a web page . Xpath is an expression
or syntax in XML language which is used to find the element using HTML DOM
structure.There are two types of Xpath :
Absolute Xpath: The absolute Xpath is the complete address of the element starting from the
HTML tag. The absolute Xpath starts from the root tag, which is the HTML tag and, traverses
down till the element tag.
SELENIUM & TESTNG NOTES
Relative Xpath: It starts with ‘//’ double forward slash which means that it can search
webelement anywhere on the webpage.
Drawback of absolute Xpath: If any changes occur in the source code between the root HTML
element and the web element, the absolute Xpath stops working because of the changes.
1. WebElement testDropDown = driver.findElement(By.id("testingDropdown"));
2. Select dropdown = new Select(testDropDown);
deselectByIndex()
deselectByValue()
deselectByVisibleText()
driver.switchTo().alert();
Once we switch the control from the main browser window to the alert window, we can
use the methods provided by Alert Interface to perform various required actions. For
example, accepting the alert, dismissing the alert, getting the text from the alert window, writing
some text on the alert window, and so on.
SELENIUM & TESTNG NOTES
Types of alerts:
1.Simple Alert
2.Confirmation alert
3.Prompt alerts.
We can handle the JavaScript popup using the Alert interface. It contains method to
switch to the alert box using the statement, Alert alert = driver.switchTo().alert(). Here,
the alert is the object reference. The above code moves the control on the alert box.
SELENIUM & TESTNG NOTES
The next statement, alert.getText() gets the message text from the alert box. If we are
not using the object reference, then we can directly write the statement
as, driver.switchTo().alert().getText().
Next, verify the text using the if-statement.
Finally, the statement alert.accept() clicks the Ok-button. Similarly, to click on the
Cancel-button, we can use the statement, alert.dismiss().
Without the object reference, the code can also be written
as driver.switchTo().alert().accept(), and driver.switchTo().alert().dismiss().
{
private int number;
//creating a constructor
DomNumber(int initialNum)
{
number=initialNum;
}
public DomNumber add(int toAdd)
{
number+=toAdd;
//returns an instance of DomNumber
return this;
}
//method to print the number
public void print()
{
System.out.println(number);
}
}
public class MethodChaining
{
public static void main(String args[])
{
DomNumber myNumber = new DomNumber(1);
myNumber.add(5).print();
}
}
Output: 6
Handling Iframes in Webpage using selenium:
In order to perform some actions on any web element present inside the
Iframe, we need to switch the driver control to the frames. So ,for this purpose
we have method called SwitchTo().frame().This method throws
SELENIUM & TESTNG NOTES
switchTo().defaultContent() Vs switchTo().parentFrame()
method
Switching back and forth between iframes and parent page can be
achieved using driver.switchTo().defaultContent() method.
Please note that there is a similar method in Selenium to switch
between frames named driver.switchTo().parentFrame () method.
The difference between driver.switchTo().defaultContent() and
driver.switchTo().parentFrame() is that the first method switches the
control to the main web page regardless of the number of frames
within the web page, while the second method switches the control
to the parent frame of the current frame.
JavaScriptExecuter in Selenium:
Syntax:
JavaScriptExecuter js = (JavaScriptExecuter)driver;
Js.executeScript(“script”,””);
JavaScriptExecuter js = (JavaScriptExecuter)driver;
js.executeScript("arguments[0].click();", button);
js.executeScript(“window.scrollBy(0,500)”);
js.executeScript(“window.scrollBy(0,document.body.scrollHeight)”);
js.executeScript("document.getElementById('Email').value='SeleniumTesting.com';");
However, there are complex interactions like Drag-n-Drop , Mouse-hover and Double-click
which cannot be done by simple WebElement commands.To achieve that selenium provides
“Actions” class. The Actions class contains a collection of actions that can be performed in
a web application.
1.Mouse actions
2.KeyBoard actions.
action.sendKeys(element, "iphone").build().perform();
action.sendKeys(Keys.ENTER).build().perform();
SELENIUM & TESTNG NOTES
For Selenium to efficiently act, there is a need for synchronization. It is the sync between
the Selenium script execution speed and the web application speed. The wait statements
SELENIUM & TESTNG NOTES
asks selenium webdriver to wait & pause the script execution for a certain length of time
until webelement appears.
While running Selenium tests, it is common for testers to get the message “Element Not Visible
Exception”. To overcome this issue, the wait statements are necessary.
driver.manage().timeout().implicitlyWait(TimeOut,
TimeUnit.SECONDS);
SELENIUM & TESTNG NOTES
Sometimes Implicit wait fails in synchronization and, it becomes necessary to use Explicit
wait in such situations. Unlike Implicit wait, which applies to all the find element
commands, Explicit wait focuses on one particular element on the web page. Explicit wait is
concept of Dynamic wait, it tells the webdriver to wait or pause the execution until some
specific condition is validated successfully within maximum allowed time.
The Explicit wait tells the WebDriver to wait for a specific condition to be satisfied within
the maximum allowed time. If it fails, then throw an exception.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
Wait.until(ExpectedConditions.VisibilityOfElementLocated(Wb));
alertIsPresent()
elementToBeClickable()
visibilityOfElementLocated()
Features of TestNG:
4. Prioritizing tests
With this, we can assign a numerical priority value to the Tests.
The default priority is 0.
5. Grouping of tests
It supports the logical grouping of test cases. Thus, providing the
ability to run the test groups in parallel, performing certain
operations before or after the execution of the tests belonging to
a group.
6. Data-Driven Testing
Using @DataProvider, we can create data-driven tests. With this
dataProvider annotation, we can pass the test data to the test
method.
SELENIUM & TESTNG NOTES
7. Reporting
After test execution, an HTML report gets created providing
tabular reporting of test results. The reporting format is also
configurable by implementing listeners.
8. Parameterization
It provides inherent support for parameterization using its
@Parameters annotation. Using @Parameters annotation, we can
pass the value of a parameter to the test logic from the testng.xml
file.
Advantages: It can be easily integrated with CI-CD tools like Jenkins.
This can be done with the help of the testNG.xml file.
With the grouping of tests, we can create different test suites like –
sanity, smoke, regression, etc. Moreover, we can integrate and trigger
those test suites with CI/CD tools like – Jenkins.
TestNG Annotations:
Annotations are basically the tags used on the top of methods which gives
some additional information & helps to control the execution/flow of Test
cases.
@BeforeSuite,@AfterSuite,@BeforeTest,@AfterTest,@BeforeTest,@BeforeCl
ass,@AfterClass,
@BeforeMethod,@AfterMethod,@BeforeGroup,@AfterGroup,@DataProvid
er,@Parameters,@Factory,@Listeners,@Ignore
groups – Used to specify the groups, the test method belongs to.
@Test(groups = { "sanity", "regression" })
alwaysRun – When set as True, the test method runs even if the
dependent methods fail.
@Test(alwaysRun=True)
public void WebLoginPersonalLoan()
{
System.out.println("Web Login Personal Loan");
}
1. <?xml version="1.0" encoding="UTF-8"?>
2. <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
3. <suite name="test_suite">
4. <groups>
5. <run>
6. <include name="SmokeTest"/>
7. </run>
8. </groups>
9. <test name="Personal Loan">
10. <classes>
11. <class name="com.javatpoint.Personal_loan"/>
12. </classes>
13. </test> <!-- Test -->
14. <test name="Home Loan">
15. <classes>
16. <class name="com.javatpoint.Home_loan"/>
17. </classes>
18. </test> <!-- Test -->
19. <test name="Car Loan">
20. <classes>
21. <class name="com.javatpoint.Car_loan"/>
22. </classes>
23. </test> <!-- Test -->
24. </suite> <!-- Suite -->
1. <test name="Home Loan" enabled=”false”>
2. <classes>
3. <class name="com.javatpoint.Home_loan"/>
4. </classes>
5. </test> <!-- Test -->
Parameters are basically the arguments passed on to the Test Methods. They are
passed via TestNG.xml file.
TestNG Parameters
TestNG DataProviders
There is an issue with TestNG parameters. We can use them to pass the
parameters to test but this happens only once per test execution. We want to run
the specific test case with different set of parameters. Then Data providers came
into picture. DataProviders pass different values to the TestNG Test Case in a
single execution and in the form of TestNG Annotations.
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.
SELENIUM & TESTNG NOTES
Optional parameters are yet another type of parameter which kind of acts like the
"default" attribute of the switch case in programming languages. So, if no
parameter value is specified, the optional parameter value is taken. Optional
parameters are those which are passed as arguments to the test methods only in
case No parameters are passed to methods.
We have all the assertions in Assert class,which has static methods like
assertEquals() etc. We can statically import the methods.
Soft Assertions are the type of assertions that do not throw an exception
immediately when an assertion fails. Therefore, all steps and soft assertions in the
automated test will execute before failing the test.
ITestListener
ITestListener: This is the most frequently used TestNG listener. ITestListener is
an interface implemented in the class , and that class overrides the ITestListener
defined methods. The ITestListener listens to the desired events and executes
the methods accordingly. It contains the following methods:
1. onStart(): invoked after test class is instantiated and before execution of any
testNG method.
2. onTestSuccess(): invoked on the success of a test
3. onTestFailure(): invoked on the failure of a test
4. onTestSkipped(): invoked when a test is skipped
5. onTestFailedButWithinSuccessPercentage(): invoked whenever a method
fails but within the defined success percentage
6. onFinish(): invoked after all tests of a class are executedThe above-mentioned
methods use the parameters ITestContext and ITestResult. The ITestContext is a
class that contains information about the test run. The ITestResult is an interface that
defines the result of the test.
Below is the configuration done in TestNG.xml file:
<suite name="Suite">
<listeners>
<listener class-name="MyListener"/>
</listeners>
<test name="Listeners_program">
<classes>
<class name="ItestListenerWithExample"></class>
</classes>
SELENIUM & TESTNG NOTES
</test>
</suite>
PAGE OBJECT MODEL(POM): Page Object Model is the design pattern of the Testing
framework which involves creating the page object repository for Web UI elements
of the Webpage. Under this page model , each page of the Web Application has a
corresponding java class which contains the action methods that needs to performed
on those web elements and a separate class which contains test methods. These java
classes act as a repository to store the various elements that we can interact with within
our test cases
POM Structure:
Class A
WebElements
Action methods
Test Methods
Class B
Applications:
Reusability :The page class designed can be reused by other classes for
different testcases
Easy Maintenance: If in future say , some UI element gets changed , then
the user has to make changes in the single class which contains the web UI
element.
SELENIUM & TESTNG NOTES
More Readable.
Page Factory: Page Factory is enhanced version of POM design version. Page
factory is basically is a class provided by selenium to implement page object
model. In Page Factory, testers use @FindBy annotation.
The initElements method is used to initialize web elements.
@FindBy: An annotation used in Page Factory to locate and declare web elements using
different locators. Below is an example of declaring an element using @FindBy
initElements(): is a static method in Page Factory class. Using the initElements method, one can
initialize all the web elements located by @FindBy annotation.
WebDriver driver;
WebElement Header;
@FindBy(xpath = "//*[@id='signupModalButton']")
WebElement getStarted;
this.driver = driver;
POM Vs PageFactory :
1. In plain POM, you define locators using ‘By’ while in Page Factory, you use FindBy
annotation to define page objects.
2. Page Object Model is a design approach while PageFactory is a class which provides
implementation of Page Object Model design approach.
3. A Page Factory is one way of implementing PageObject Model which is inbuilt
in selenium.
SELENIUM & TESTNG NOTES