*Handling Frames:
Difference between Frame and Iframe:
Frame is a HTML tag that is used to divide the web page into various frames/windows. Used as <frame> tag, it specifies each frame within a frameset tag. Iframe as <iframe> is also a tag used in HTML but it specifies an inline frame which means it is used to embed some other document within the current HTML document.
* Syntax for handing frame: we can identified frame in three approaches
driver.switchTo().frame(name/id)
driver.switchTo().frame(WebElement)
driver.switchTo().frame(index)
1)driver.switchTo().frame("packageListFrame");
we use switchto() in order to switch between the frames and we pass Specific frame name
2)WebElement frame2=driver.findElement(By.xpath("//frame[@src='frame_2.html']"));
driver.switchTo().frame(frame2);
here we identified the frame as webelement and stored in variable and passes that variable in frame()
3)driver.switch.frame(0);
here we used index of the frame .f there are multiple iframes on a web page, we can switch to each one of them using the index of the iframe in Selenium.
*We use driver.switchTo().defaultContent(); statement to switch back to main webpage from frame .
* Handling BrowserWindow:
getWindowHandle() - return id of single window( in which driver focused)
getWindowHandles()- returns id's of multiple windows
driver.switchTo().window(window id)//switch to perticular window
driver.switchTo().window(window id).getTitle()
*driver.getwindowhandles(); will return all window ids
*Step1:First store all windowIds in one Set of String variable
Set<String> ids=driver.getWindowHandles();
converting set to list becuase set not allow index method so it will not allow.get() methods for retrieving window ids so set converted to list
Step2:List<String>Windowids=new ArrayList(ids);//convert to list
Step3:Identify parent and child window ids
String parentwindow=Windowids.get(0);
String Childwindow=Windowids.get(1);
Step4:Now switch to specifc window and perform actions
driver.switchTo().window(Childwindow);
driver.findElement(By.xpath("//a[@href='/en/contact-sales/']//button[@class='btn btn-ohrm btn-free-demo'][normalize-space()='Contact Sales']")).click();
//switching to parent window
driver.switchTo().window(parentwindow);
driver.findElement(By.xpath("//input[@placeholder='Username']")).sendKeys("Admin");
Step5:Closing perticular window
write a enhanced loop and store title of all browsers in one variable and compare title
If the browsertitle is equals to speicifed title then user driver.close();
for(String Windowids2:ids)
{
String title1=driver.switchTo().window(Windowids2).getTitle();
if(title1.equals("OrangeHRM HR Software | Free & Open Source HR Software | HRMS | HRIS | OrangeHRM"))//this is title of child window so child window closes
{
driver.close();
}
*Handling static tables:
There are two types of HTML tables published on the web-
- Static tables: Data is static i.e. Number of rows and columns are fixed.
- Dynamic tables: Data is dynamic i.e. Number of rows and columns are NOT fixed.
Web Tables are used to organize similar types of content on the web page, Web tables are groups of elements that are logically stored in a row and column format. Web table has various HTML tags like., table, th, tr, td. Let’s understand these tags a bit more:
- <table> – It defines a table
- <th> – It defines a header cell
- <tr> – It defines a row in a table.
- <td>- It defines a cell in a table. the <td> tag always lies inside the <tr> tag.
// 1) Find total number of rows
int numofrows=driver.findElements(By.xpath("//div[@class='widget HTML']//table[@name='BookTable']//tr")).size();
/2) Find total number of column
int numofcolums= driver.findElements(By.xpath("//table[@name='BookTable']//th")).size();
//3) Read specific row & column data
String value=driver.findElement(By.xpath("//table[@name='BookTable']//tr[4]//td[1]")).getText();
System.out.println(value);
//4) Read data from all the rows & columns
for(int r=2;r<=numofrows;r++)
{
for(int c=1;c<=numofcolums;c++)
{
String data= driver.findElement(By.xpath("//table[@name='BookTable']//tr[\"+r+\"]//td[\"+c+\"]")).getText();
System.out.println(value);
}
}
//5)Print book names whose author is Amit
/*for(int r=2;r<=numofrows;r++)
{
String author=driver.findElement(By.xpath("//table[@name='BookTable']//tr["+r+"]/td[2]")).getText();
if(author.equals("Mukesh"))
{
String bookname=driver.findElement(By.xpath("//table[@name='BookTable']//tr["+r+"]/td[1]")).getText();
System.out.println(author+" "+bookname);
}
}*/
//6)Find sum of prices for all the books
int sum=0;
for(int r=2;r<=numofrows;r++)
{
String price=driver.findElement(By.xpath("//table[@name='BookTable']//tr["+r+"]/td[4]")).getText();
sum=sum+Integer.parseInt(price);
}
System.out.println("Total price of books:"+sum);
}
*Mouse Actions
--------------
What is Action Class in Selenium?
Actions class is an ability provided by Selenium for handling keyboard and mouse events. In Selenium WebDriver, handling these events includes operations such as drag and drop in Selenium, clicking on multiple elements with the control key, among others.
Action class is defined and invoked using the following syntax:
Actions action = new Actions(driver);
action.moveToElement(element).click().perform();
Methods of Action Class
Action class is useful mainly for mouse and keyboard actions. In order to perform such actions, Selenium provides various methods.
Mouse Actions in Selenium:
- doubleClick(): Performs double click on the element
- clickAndHold(): Performs long click on the mouse without releasing it
- dragAndDrop(): Drags the element from one point and drops to another
- moveToElement(): Shifts the mouse pointer to the center of the element
- contextClick(): Performs right-click on the mouse
*Actions class is provided by selenium webdriver
*build() - create an action AND perform() - can complete the action
* What is the difference between Gettext() and GetAttribute(value);
As the name suggests, the getAttribute method gets the value of a given HTML attribute. On the other hand, getText() returns the inner text of a given element. The term “inner text” means the text located between the opening and closing tags of the element
example:
<input id='abc' > testing</input> testing - inner text
findElement(Loc).getText() ----- testing
findElement(Loc).getAttribute('value') - return nothing
<input id='abc' value='testing' /> no innertext
findElement(Loc).getText() - return nothing
findElement(Loc).getAttribute('value') --- testing
* What is the difference between build() and Perform() in selenium?
build() method in Actions class is use to create chain of action or operation you want to perform.
perform() this method in Actions Class is use to execute chain of action which are build using Action build method.
* Difference between Action interface and Actions class?
Action interface is basically representing Composite Action which we built from a sequence of multiple actions. or Actions interface stores the all the sequence of actions in Action variables and And finally, perform the actions sequence using perform() method of Action Interface.
Example:
WebElement button=driver.findElement(By.xpath("//span[@class='context-menu-one btn btn-neutral']"));
Actions act=new Actions(driver);
act.contextClick(button).build().perform();//direct;y performing action
Action myaction=act.contextClick(button).build();//creating action and storing it in variable
myaction.perform();// using action interface for performing stored action when ever we want in the script
so we use action interface if we dont want to perform action immidiatly if we want to perform later action. in that scenario first we build chain of actions and store in Action interface variable
then later when ever we can to Perform() we can perform it simply by using Action interface varible .perform()
ifferent Methods for performing Mouse Events:
click(): Clicks at the current mouse location.
doubleClick(): Performs a double-click at the current mouse location.
contextClick() : Performs a context-click at middle of the given element.
clickAndHold(): Clicks (without releasing) in the middle of the given element.
dragAndDrop(source, target): Click-and-hold at the location of the source element, moves to the location of the target element
dragAndDropBy(source, xOffset, yOffset): Click-and-hold at the location of the source element, moves by a given offset
moveByOffset(x-offset, y-offset): Moves the mouse from its current position (or 0,0) by the given offset
moveToElement(toElement): Moves the mouse to the middle of the element
release(): Releases the depressed left mouse button at the current mouse location
*What are KeyBoard Events:
A Keyboard Event describes a user's interaction with the keyboard. When a user presses single or multiple keys, keyboard events generate. Selenium provides various ways to automate these Keyboard Events
driver.get("https://text-compare.com/");
driver.findElement(By.xpath("//textarea[@id='inputText1']")).sendKeys("Welcome to automation");
Actions act=new Actions(driver);
//contrl a
act.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
//contrl c
act.keyDown(Keys.CONTROL).sendKeys("c").keyUp(Keys.CONTROL).perform();
//tab
act.keyDown(Keys.TAB).keyUp(Keys.TAB).perform();
//act.sendKeys(Keys.TAB).perform(); // only if want to press single key then prefer this
//contl v
act.keyDown(Keys.CONTROL).sendKeys("v").keyUp(Keys.CONTROL).perform();
* How we can open url in next tab or in different browser?
We can do that using switch statment like below
driver.get("https://www.opencart.com/");
driver.switchTo().newWindow(WindowType.TAB);//opens in new tab in same browser
driver.switchTo().newWindow(WindowType.WINDOW);//opens in another window
driver.get("https://opensource-demo.orangehrmlive.com/");
----------------------------------------------------------------------------------------------
What is javascriptexecutor?
Javascriptexecutor is an interface which is having ExecuteScript Method.
We use Javascriptexecutor when ever their is delay in actions .example
internally sendkeys("bindu") is calling function which is called by ExecuteScript method present in interfaceJavascriptexecutor when their is dealy sendkeys will work will get interuot exception then we use Javascriptexecutor to perform actions on webpage.
ExecuteScript() :
we can execute java script statemetns in selenium using this method...
Example://for sending input
WebElement inputbox=driver.findElement(By.id("RESULT_TextField-1"));
js.executeScript("argument[0].setAttribute('value','bindu')", inputbox);
//Radio button
WebElement male_Rd=driver.findElement(By.id("RESULT_RadioButton-7_0"));
//male_Rd.click(); //ClickInterceptedException so when this error occurs we use JavascriptExecutor
js.executeScript("arguments[0].Click()", male_Rd);
*One more live example where we use JavaScriptExecutor is scrolling page
JavascriptExecutor js=driver;
//1) scroll down page by pixel
//js.executeScript("window.scrollBy(0,3000)", "");
//System.out.println(js.executeScript("return window.pageYOffset;")); //3000
//2) scroll down the page till the element is present
//WebElement flag=driver.findElement(By.xpath("//img[@alt='Flag of India']"));
//js.executeScript("arguments[0].scrollIntoView();", flag);
//System.out.println(js.executeScript("return window.pageYOffset;")); //5077.40234375
//3) scroll down till end of the page/document
js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
System.out.println(js.executeScript("return window.pageYOffset;"));
Thread.sleep(3000);
// go back to initial position
js.executeScript("window.scrollBy(0,-document.body.scrollHeight)");
?
* What are Broken Links and How they can handle?
A broken link is a web-page that can't be found or accessed by a user, for various reasons. Web servers will often return an error message when a user tries to access a broken link. Broken links are also often known as “dead links” or “link rots
Common Reasons for Broken Links
- 404 Page Not Found – The destination web page has been removed by the owner
- 400 Bad Request – The server cannot process the HTTP request triggered by the link because the URL address requested is wrong
- Use the following steps to identify broken links in Selenium
- 1)Use <a> tag to fetch all the links present on a web page
- 2)Send HTTP request for the link
- 3)Verify the HTTP response code for the link
- 4)Determine if the link is valid or it is broken based on the HTTP response code
- 5)Repeat the process for all links captured with the first step
* How to capture screenshort ?
A Screenshot in Selenium Webdriver is used for bug analysis. Selenium webdriver can automatically take screenshots during the execution. But if users need to capture a screenshot on their own, they need to use the TakeScreenshot method which notifies the WebDrive to take the screenshot and store it in Selenium.
Steps:
//Convert web driver object to TakeScreenshort
1)TakesScreenshot ts=(TakesScreenshot)driver;
//Call getScreenshotAs method to create image file
2)File src=ts.getScreenshotAs(OutputType.FILE);
// Copy file to Desired Location
3)File trg=new File("C:\\\\Users\\\\abc\\\\eclipse-workspace\\\\SeleniumProject\\\\ScreenshortsFolder\\Screenshort.png");
FileUtils.copyFile(src, trg);*/
What is headless testing?
Headless mode is a functionality that allows the execution of a full version of the browser while controlling it programmatically.
They are executed via a command-line interface or using network communication. This means it can be used in servers without graphics or display, and still, the Selenium tests run!
Syntax:
//////// chrome browser ///////////
//Appraoch1) Headless mode
/*ChromeOptions options=new ChromeOptions();
options.setHeadless(true);
WebDriverManager.chromedriver().setup();
WebDriver driver=new ChromeDriver(options);
----------------------------------------------------------------------------------------
What is datadriven testing?
Data Driven Testing is a software testing method in which test data is stored in table or spreadsheet format. Data driven testing allows testers to input a single test script that can execute tests for all test data from a table and expect the test output in the same table. It is also called table-driven testing or parameterized testing.
- Data-driven is a test automation framework which stores test data in a table or spread spreadsheet format.
- In Data-driven test automation framework, input data can be stored in single or multiple data sources like xls, XML, csv, and databases.
- Allows to test application with multiple sets of data values during Regression testing
- Test data and verification data can be organized in just one file, and it is separate from the test case logic.
Disadvantages:
- Data validation is a time-consuming task when testing large amount of data.
- Maintenance is a big issue as large amount of coding needed for Data-Driven testing.
*Testng testing
* Testng will execute test in alphabetical order so in order to run as per requirement we make prioroties so that first number will execute based on prioroties
*If we not mentioned @test annotation to method then teng will not execute that method
*Evry function will have pre-requisite and exit criteria for example login application tpre=requisite is Launch browser and Exit criteria id Logout so we mentioned PRE-REQUITE method as @beforeclass and Exitxriteris as @Afterclass.And login function mentioned with @Test annotation then we can see output only @test method only.
*Testng will not consieder @Afterclass and @Before class as test methods .Testng will execute @Afterclass and @Beforeclass but it will consider as test thats why we cannot see result screen
@BeforeMethod:
before method will excute first multiple times before executing the every test method in the class
@Aftermethod will execute first mutiple times after completion of the every test method in class
@Before class
Before class will execute once before starting all the test methods
@AfterClass
After class will execute once after completion of all the test methods
@Before Test
Beforetest will execute multiple times before every test in xml
@AfterTest
Aftertest will execute multiple times after evry test in xml
@Before suite
Before suite will execute once before the execution of Suite
@Afet suite will execute once after the completion of suite
XML-->Test-->Classes-->Mehtods
->DependesOnMethods
*TestNG DependsOnMethods gives you control over how you run your test cases
*Using 'dependsOnMethod' attribute within @Test annotation, we can specify the name of the parent test method on which the test should be dependent. On execution of the whole test class or test suite, the parentTest method will run before the dependentTest.
example.
*If parent method got failes then following child Test methods which are dependent on parent method will be skipped.In this way we can control over run of our test cases
example:
@Test(priority=1)
void openapp()
{
Assert.assertTrue(true);
}
@Test(priority=2, dependsOnMethods= {"openapp"})
void login()
{
Assert.assertTrue(true);
}
@Test(priority=3, dependsOnMethods= {"login"})
void search()
{
Assert.assertTrue(false);
}
@Test(priority=4,dependsOnMethods= {"search"})
void advsearch() {
Assert.assertTrue(true);
}
@Test(priority=5,dependsOnMethods= {"advsearch"})
void logout()
{
Assert.assertTrue(true);
}
* DIFFERENCE BETWEEN HARD AND SOFT ASSERTION
*HardAssertion:
1)The assertion is an expression that is used to check the expected and actual results of a test case. It is used to make sure that the actual result matches the expected result
2)Test execution will be aborted if the assert condition is not met.
3)These should be used in scenarios where it is required to halt the test execution if a critical test step results in a failure.
4)access though 'Assert' class
Assert.asserequals();
*SoftAssertions
1)Verification is a process of validating or confirming that the expected behavior of the application is happening.
2)Test execution will continue till the end of the test case even if the assert condition is not met.
3)These should be used in scenarios where the failure of certain conditions does not hamper the execution of other test steps in that method.
4)access through 'SoftAssert' object
SoftAssert sa=new SoftAssert();
sa.assertTrue()
example:
Login any application if faiure comes due to invalid credentials then execution of remaining Test methods like Search and Logout shod stop.
* What is DataProvider and its usage?
DataProvider feature is one of the important features provided by TestNG. It is the second way of passing parameters to test methods.
It allows the users to write data-driven tests in which we can run multiple times the same test method with different sets of test data.
DataProvider is a method in a class that returns a two-dimensional array of object (Object [ ][ ]) to the test method.
example:
package Pack12;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DataProviderDemo {
WebDriver driver;
@BeforeClass
void setup()
{
WebDriverManager.chromedriver().setup();
driver=new ChromeDriver();
}
@Test(dataProvider="dp")
void testLogin(String email, String pwd)
{
driver.get("https://demo.nopcommerce.com/login");
driver.manage().window().maximize();
driver.findElement(By.id("Email")).sendKeys(email);
driver.findElement(By.id("Password")).sendKeys(pwd);
driver.findElement(By.xpath("//button[normalize-space()='Log in']")).click();
String exp_title = "nopCommerce demo store";
String act_title = driver.getTitle();
Assert.assertEquals(exp_title, act_title);
}
@AfterClass
void tearDown()
{
driver.close();
}
@DataProvider(name="dp",indices= {0,2,3})
String[][] logindata()
{
String data[][]={
{ "abc@gmail.com", "test123" },
{ "pavanol@gmail.com", "test@123" },
{ "pavanoltraining@gmail.com", "test3" },
{ "pavanoltraining@gmail.com", "test@123" },
{ "pavanoltraining@gmail.com", "test@123" }
};
return data;
}
}
*Parallel Testing:
Parallel Testing is a software testing type in which multiple versions or subcomponents of an application are tested with same input on different systems simultaneously to reduce test execution time. The purpose of parallel testing is finding out if legacy version and new version are behaving the same or differently and ensuring whether new version is more efficient or not.
- To make sure the new version of the application performs correctly
- To make sure the consistencies are same between new and old version
- To check if the data format between two versions has changed
- To check the integrity of the new application
*Parameter testsing
1)Parameterized tests allow developers to run the same test over and over again using different values.
2)TestNG lets you pass parameters directly to your test methods in two different ways −
With testng.xml
With Data Providers
3) TestNG Using @Parameters Annotation in xml file and define value, now in script we pass this value as input parameter
<suite parallel="tests" thread-count="2" name="my suite">
<test name="test1">
<parameter name="browser" value="Chrome"/>
<parameter name="url" value="https://opensource-demo.orangehrmlive.com"/>
script
@BeforeClass
@Parameters({"browser","url"})
void setup(String br,String appurl)
{
if(br.equals("chrome"))
{
WebDriverManager.chromedriver().setup();
driver=new ChromeDriver();
* Listernes
TestNG Listners
-------------
*Listeners are TestNG annotations that literally “listen” to the events in a script and modify TestNG behavior accordingly. These listeners are applied as interfaces in the code. For example, the most common usage of listeners occurs when taking a screenshot of a test that has failed and the reason for its failure
ITestListener is a ---> Interface
TestListenerAdapter -- Class
onTestStart()
onTestFailure()
onTestSuccess()
onTestSkipped()
In order to create an Extent report we need to following steps
1)need to copy extent report dependency from maven to pom.xml files and update project
2)Create a Test case and create Report folder in Project
3)Creat listeners class ,and in this mention where we need to save the generated report file
4)create a Testng.xml file,in that agg <Listeners> tag and in that tag mention the listeners class name
4)once we execute testng.xml file report will generated in metioned path. that is in report folder.
*What is PageObject Model?
Page Object Model, also known as POM, is a design pattern in Selenium that creates an object repository for storing all web elements. It helps reduce code duplication and improves test case maintenance.In Page Object Model, consider each web page of an application as a class file.
Advantages
- Easy Maintenance: POM is useful when there is a change in a UI element or a change in action. An example would be: a drop-down menu is changed to a radio button. In this case, POM helps to identify the page or screen to be modified. As every screen will have different Java files, this identification is necessary to make changes in the right files. This makes test cases easy to maintain and reduces errors.
- Code Reusability: As already discussed, all screens are independent. By using POM, one can use the test code for one screen, and reuse it in another test case. There is no need to rewrite code, thus saving time and effort.
P* Page Factory is a class provided by Selenium WebDriver to support Page Object Design patterns. 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
@FindBy(id="elementId") WebElement element;
-----------------------------------------------------------------
*If you want to run testng.xml files through pom.xml then steps need to follow
Step1)Copy maven-surefire-plugin and paste in pom.xml before deoendencies
Step2)copy maven-compiler-plugin and paste in pom.xml before dependencies.
Step3)Update project and from pom.xml right click run as maven test.
* to run test methods from command prompt then steps are brlow:
How to run project from command prompt steps
Step1) Download Apache Maven for windows from website
Step2)Pom.xml file will run the teng.xml file in eclipse level but if we want to run at the Operating system level that is through the command prompt we need to download Mavanen repository and Save in Local Disk c and set the path in environmental variables.
download path
https://maven.apache.org/download.cgi
Step3)Once downloaded and saved in local disk c and also
Step4)Now set path in environmental variables like create new variable
variable name: Maven _Home
varibale value: c://apache_maven-3.9.4
and also set path that its
path://%maven_Home%/bin
Step5) Then open command prompt and check whether maven installed or not using
mvn -version
Step6) from the command prompt we need to go to the current project location for that we need to enter the current project location type below command in the command prompt and press enter
cd C:\Users\abc\eclipse-workspace\OpenCart
Step7)to run pom.xml from a command prompt enter the below command
mvn test
Step8) If you want to run from the bat file just one single click pom.xml will execute in the command prompt for that first we need to create one file in the current project location and copy below two statements in that file and save it as run.bat file then double click that file pom will execute in command prompt
cd C:\Users\abc\eclipse-workspace\OpenCart\
mvn test
* cls to clear the command prompt
====================================================================================================
Steps for downloading git in local system
Step1)Open the below link and download GitHub for windows in the system clicknext next..and finish
https://git-scm.com/download/win/
Step2)Signup for github reporitory
first, push the from eclipse workspace to git(local repository ) and from git to github(remote repository)
Commands of git:
Step1) $ git init
Initialized empty Git repository in C:/Users/abc/eclipse-workspace/OpenCart/.git
1st round
-----------------------
1) git init ---> create an empty local repository
2) git config --global user.name "your name"
git config --global user.email :your email"
3) git add -A ---> add all the files and folders to staging area
git add filename.txt
git add *.java
git add foldername
4) git commit -m "commit msg"
5) git remote add origin "github URL"
6) git push -u origin master
2nd round
---------
1) git add -A
2) git commit -m "commit msg"
3) git push -u origin master
git pull --> get files from github to workspace
clone - get entire project into your workspce
git clone "github repo url" <folder> <br>
Comments
Post a Comment