0
1) How to handle ajaxobject/dynamic object.
Ans:we canusecontains() function
Eg. <input id=’email’type=’email’ />
Xpath : //input[contains(@id,’ema’)]
2) What is webdriverjava interface?
Ans:
Technically webdriver is a collection ofinterfaces andclass
Webdriver is a webbasedautomation testing tool, it uses api todrive the test onthebrowser
Webdriver as nativesupport’s almost allthebrowsers
3)How do you identify theobjects? In what scenarios theselocators areused?
Ans:
Id linktest
Name partiallink
Xpath tagname
Css locatorclassname
4) How to work withbutton which is indiv tag andyou haveto click withoutusing xpath.
Ans: using submit() OR using sendkeys(keys.enter)
5)How to pass keyboard operations
Ans: wb.sendkey(key.downkey)
6) How to work withweblist@radiobuttonin webdriver. Or howto work with weblist (dropdown)
Ans: we createobject ofselect class anduseobjectto select.
Eg. Webelement webele=driver.findelement(By.name(“”));
Select select =new Select(webele)
select.selectbyvisibletext(“abc”);
Thread.sleep(2000);
select.selectByvalue(“s”);
7)multiple selectlistbox
Ans: webdriverdriver=new firefoxdriver();
Driver.get(“file”);
Select sel=newSelect(driver.findelementby( “”));
Sel.selectbyvisibletext(“a”);
Sel.selectbyvisibletext(“b”);
8)How to get text from UI.
Ans:
Come to name (Independentvalue)
Sibling (which is dependent )
Then get value ofA intostring
Eg. Driver.findelement(by.linktext(“projects abd customer”)).click();
Driver.findelement(by.linktext(“aaa”).click());
String expectedCustname=driver.findelement(by.xpath(“”));
String actcustname=’a’;
SOP(actcustname.equals(expectedCustname));
9)How to handle dynamicdropdown
Ans:
Eg. WebElementwb=driver.findElement(By.name(“”));
Select selcust=new Select(wb);
List<WebElement>custlist=selcust.getOptions();
SOP(custlist.size());
String expectedVal=”abc”;
Boolean flag=false;
For (int i=0;i<=custlist.size(); i++){
String actualVal=custlist.get(i).getText();
If(expectedVal.equals(actualVal)){
SelCust.SelectByVisibleText(expectedVal);
1
Flag=true;
Break;}
If(flag)
{sop(“value not indropdown”);}}
10)How to verifiy colour oftext orimage.
Ans: <h1 class=”redtext”>GMAIL</h1>
Fetch value ofclass attribute
Driver.FindElement(locator).GetAttribute(“class”)
11)How to check which tab is enabled
Ans Use GetAttribute
12)Check howmany links presentin UI and click onlink5 suppose.
Ans: Webdriverdriver=newFirefoxDriver();
Driver.get(“ ”);
Int a =driver.findElement(By.xpath(“”));
List<WebElement>listOfLinks=driver.findElement(By.xpath(“”));
Sop(listOfLinks.size());
String expectedLink =”Switch togmail”;
Boolean flag=false;
For(int i=0;i<listOfLinks.Size();i++){
String actVal=listOfLink.get(i).getText();
If(expectedLink.equals(actVal))
{
Driver.findElement(By.linkText(ExpectedLink).click());
SOP(“link text present”);
Flag=true;
Break;
}
If (! flag)
{
SOP (“link not present”);
}
13) Difference between Implicitwaitandexplicitwait.
Ans: also fluentwait
Implicitwait Explicit wait
In Implicit wait, tell’s webdriverto poll thedom{xml,html}document
for a certain amountoftimewhentrying to find anelement.
Wait tillelementis presentin UI
Waits tillpage gets downloaded Generally webdriver waitcheckexpected conditionby every500
milliseconds ifelement found within specified amountof
time,webdriver nextstepexecution(notgoing to waitfor entire
10sec)
If page gets downloadedwithinspecifiedamount oftime, webdriver
dos not wait for specified time, itwill continuethenext step
execution.
Does not throwanyexception
Disadvantage: Ajaxapplication wait doesn’t work
Driver.manage().Timeouts().ImplicitWait(10000,TimeUnit.secounds)
/.hours/.milisecounds/.days
WebdriverWait wait=new WebDriverWait(driver,10);
Wait.Until(ExpectedCondition.elementToBeClickable(locator));
14) How to check whetherbuttonis enabled or not.
Ans: driver.findElement(By.name(Username).isEnabled();
.isSelected();
.isDisplayed();
All methods aregoing toreturnBoolean;
15) How to handlewindow popup?
Ans:
Set<String>WinList1=driver.getWindowHandles();
2
Iterator<String>it1=WinList1.iterator();
String parentWinId=it1.next();
Stirng ChildWinId=it1.next();
Driver.switchto.Window(ChildWinId);
Perform actions on child window thenpass controlback toparent window
Close current window
Driver.close();
Driver.switchto.Window(ParentWinId);
Driver.close();
Driver.quit();
When an action calls a pop upto open a new window, webdriverdoes not automatically takecontrol ofthenew popup window.Transfer
control to child window.
17) Once we click anylink automatically weget lots ofpop up.How toget the desiredone.
Ans: Will haveset ofwindow id’s. Using HasNext() iterateto allthewindowGetTitle() andcheck ifwindow titleis sameas required.
18) How to handlealert?
Ans: Alert alt =driver.SwitchTo.alert();
SOP(alt.getText());
Alt.accept();
Alt.dismiss();
19) How to countno. ofalert present in UI.
Ans: int count;
Boolean flag=true;
While(flag)
{
Try{
Alert alt=driver.SwitchTo.alert();
Count=count+1;
Alt.accept();}
Catch(no alert presentexceptione)
{Flag=true ;}
}
2)How to switch toframe?
Ans: find element byiframetag
Driver.get(“times ofindia”);
Thread.sleep(1000);
Driver.switchTo.frame(“id”);
Driver.findElement(locator).sendkeys(“10”);
21)What is the useofActions class inwebdriver? OR howto workwith keyboard and mouseoperations?
Ans: Mouse actions:(Action classes)
movetoElement();
draganddrop();
contextClick();
sendkeys();
Eg. Actions act=new Actions(driver);
Act.dragAndDrop(SourceWeb,destination).build().perform();
Actions act =new Actions(driver);
Act.sendkeys(keys.Tab,keys.Enter).build.perform();
Move to mousemoment
Actions act=new Actions(driver);
Act.moveToElement(wb).build().perform();
Driver.findElement(locator).click();
Right click operation
Action act=newActions(driver);
Act.contextclick(sourceweb).build.perform();
22)How to handle googlesearch text? OR Autosuggest/Autocompleteeditbox.
Ans: driver.get(URL“);
3
Driver.findElement(By.id(“locator”)).sendkeys(“value”);
Driver.findElement(By.xpath(“”)).click();
List<Weblist>str=driver.findElement(By.xpath(“locator”));//capture allthecoming suggestions and display the list.
For(i=0;i<=str.size()-1;i++)
{
Sop(str.get(i).getText());
}
23)How wouldyou doproxy settings using webdriver. Samoriginpolicy
Ans:
firefoxProfile profile=newFirefoxprofile();
profile.setpreferences(“network.proxy.type”,1);
profile.setpreference(“network.proxy.http”,’localhost”);
profile.setpreference(“network.proxy.http_port”,3128);
Webdriver driver=new Firefoxdriver(profile);
24)How to work withhttps websiteOR howto handleSSL certificationin Firefox
Ans:
FirefoxProfileprofile=new firefoxProfile();
FirefoxProfile.SetAssumeUntrustedCertificateIssue(false);
Driver=newFirefoxDriver(fireforxprofile);
Driver.get(“https://google.com”);
25)Delete system cookies
Ans: WebDriverdriver=new FirefoxDriver();
Driver.manage().deleteAllcookies();
26) How to work with file attachment andfiledownload inwebdriver. AutoIt
Ans:
1)if editbox is not disabled wecan attachfileusing sendkeys();
2)Use AutoIT of edit boxis disabled.
#include<IE.au3>
$oShell=ObjCreate(“Shell.application”);
$oShallWindows =$oshell.windows;
WinActive(“FileUpload”);//checkifupload window is active
$file=”filepath”;
ControlSetText(“File Upload”,”Edit”,$file);
ControlClick(“FileUpload”, “Button1”);
3)Convert .au3to .exefile
4)call .exe in eclipse
In eclipse PSVM()
{
Runtime.getRuntime().exec(pathofexefile);
}
33)File Upload using sendkeys
Ans
Public class uploadfiles
{public staticvoidmain(Stirng args[])
{
FirefoxDriverdriver=newFirefoxDriver();
Driver.get(URL);
File file=null;
Try
{
File =new File(path);
}Catch(Exception e)
{
e.printStackTrace();
}
Assert.assertTrue(file.exists());
WebElementbrowserbutton=driver.findElement(By.id(“locator”));
4
browserButton.senkeys(file.getAbsolutePath());
}
}
27)How to handle calender pop up?
28)Read data fromexcel sheet?
Ans: Apache OPIlibraries
PSVM()
{
FileinsputStreamfs=new FileInputStream(“”);
Workbook ws=WorkbookFatory.Create(fs);
Sheet sh=ws.getSheet(“sheet name”);
Int rowCount=getRowCount(“Sheet1”);
For(int i=1;i<=rowCount;i++)
{
String testCaseName=sh.getRow(i).getCell(0).getStringCelValue();
TestCaseDsc=sh.getRow(i).getCell(1).getStringCellValue();
}
}
29)Write data to Excel sheet
Ans: PSVM()
{
FileInputStreamfs=new FileInputStream();
Workbook wb=WorkbookFactory.Create(fs);
Sheet sh=wb.getSheet(“sheetname”);
Row rw=sh.getRow(1);
Cell cel=rw.createCell(6);
Cel.SetCellType(cel.Cell_TYPE_STRING);
Cel.setCellValue(“abcd”);
FileOutputStreamfos=new FileoutputStream(“”);
Fos.write(fos);
}
30)Write syntax for finding therow count indynamic webtable
Ans:
//Function
Public HasMap<String.String>getRowData(String xpathRowElement)
String row=Driver.findElement(By.xpath(xpathRowElement)).getText();
SOP(row);
String[]rowArray=row.Split(“”);//split by space
Hashmap<String,String>rowData1=new HashMap<String,String>;
rowData1.put(“Customer/projects”,rowArray[0]);
rowData1.put(“AddTask/projects”,rowArray[1]+rowArray[2]);
return rowData1;
}
//In test case
HashMap<String,String>CustomerRowData=getRowData(“xpath”);
If(CustName.equals(CustomerRowData.get(“Customer/projects”)))
{
SOP(customerrowdata)
}
String task=”0”
If(task.equals(customerRowData.get(Opentask“)))
{SOP(customerRowData(“OpenTask”));
}
31)TestNG and Advantages
Ans:
Testing is a framework usedfor core java unittesting
It does not havea UI . It’s a collection of.jar files.
TestNG does nothavea mainmethod torun a class whichuses annotations toidentify thetest.
5
testing executemultiple test cases through TestNG-XMLfileand generateaHTMLreportwithout any manual intervention.
32)TestNG annotations.
Ans;
@Test @Beforemethod
@Aftermethod @BeforeClass
@Afterclass @Beforesuite
@AfterSuite grouping using @DataProvider
Parallelexecution
TestNG method should bevoid. Does notreturnanything. One TestNG class canhave multipletest.
33)What arethedifferent arguments arepassed along with @Test annotationin TestNG?
Ans:
34)Group executionin TestNG-XLMfile
Ans:
//Suppose wehave
Public class VerifyCustomerField{
@Test(groups={“feature1”,TestCreateCustomer})
Public void verify customer()
{
SOP (“Test1”);
}
Public class CustomerandprojectTest{
@Test(groups={“feature1”,TestCustomer&Project})
Public void verify customer&Project()
{
SOP (“Test2”);
}
//TestNG-XML looks like
<Suite name=”Suite”parallel=”None”>
<test name=”Test”>
<groups>
<run>
<include name=”feature1”></include>
</run>
</groups>
//Or another example
<classes>
<class name=”VerifyCustomerField”>
<class name=”CustomerandprojectTest”>
</classes>
</test>
</suit>
35)How to include andexcludethegroups in the testing XMLfile?
Ans: <excludename=”groupname”></exclude>
36)How to achieveparallel execution inTestNG.
Ans:
<Suite name=”Suite”parallel=”tests” preserve-order=”true”>
<test name=”Test”preserve-order=”true”>
<classes>
<class name=”VerifyCustomerField”>
<class name=”CustomerandprojectTest”>
</classes>
</test>
</suit>
6
37)what are thedifferent arguments passedto testing
Ans:
@Test(dependsOnMethod={“”loginTest})
Public void testCreateCustomer()
{
SOP(“create cusotmer”);
}
@Test
Public void loginTest()
{
SOP(“login”);
}
@Test(dependsOnMethod={“”TestCreateCustomer})
Public void logout()
{
SOP(“logout”);
}
38)parallelexecution
Ans:
Test in parallel
<Suite name=”suite”parallel=”tests”preserve-order=”true”thredcount=”5”>
Method in parallel
<Suite name=”suite”parallel=”methods” preserve-order=”true” thredcount=”5”>
Classes in parallel
<Suite name=”suite”parallel=”classes”preserve-order=”true”thredcount=”5”>
45)What arethetypes ofassertions and what areassertions intesting
Ans:
Eg. If you want to failtestcases:
Public class test1
{
@Test
Public voidloginTest(){
String actualName=”abc”;
String expectedname=”ab”;
If(actualName.equals(expectedname))
{
Assert.assertTrue(true,’Test is pass’);
}
Else
{
Assert.assertTrue(false,”Test is fail”);
}
}
39)Types of assertions
Ans:
AssertTrue() AssertFalse()
AssertEquals() AssertNotEqual()
AssertSame() AssertNotSame()
AssertNull AssertNotNull
Eg: @Test
Public void login()
{
Generic lib=newgenericlib();
Try{
Assert.assertTrue(lib.login(“admin”,”password”),”Customer not matching”);
}Catch(Throwablee)
{
SOP(catch block}}
40) Most commonExceptions:
7
1) NoSuchElementException : FindBy method can’t find the element.
2) StaleElementReferenceException : This tells that element is no longer appearing on the DOM page.
3) TimeoutException: This tells that the execution is failed because the command did not complete in enough time.
4) ElementNotVisibleException: Throw n to indicate that although an element is present on the DOM, it is not visible, and so is not
able to be interacted w ith
5) ElementNotSelectableException: Throw n to indicate that may be the element is disabled, and so is not able to select.
41)How to takescreenshots?
Ans:
Psvm(String[]args)
{
WebDriver driver=new FireFoxWebDriver();
Driver.get(weblink);
EventFiringWebDriver edriver=new EventFirinfWebDriver();
File srcImg=edriver.getScreenShotAs(OutputType.FILE);
File destImg=newFile(file location);
FileUtils.copyFilesToDirectory(srcImg,desImg);
}
42)Differenceget() and navigate().to();
43)How to do data parameterization? What is data provider?
Ans: To do a parameterization
Running sametestscript withmultiple data
Test data from excelsheet,or xml sheet.
Eg.
Public class testNgDataProvider{
@Test(dataProvider=”getData”)
Public void checkAccountStatusTest(String accname,String Psw)
{
SOP(accname);
SOP(Psw);
}
}
@DataProvider
Public Object[][]getData()
{
Object[][]data=new Object[5][2];
Data[0][0]=”Act1”;
Data[0][1]=”Pass1”;
Return data;}
51)What is selenium grid
As: Want to runtestscripts on differentmachines, different browsers acts like remotecontrol.
Eg.
Public class selenium grid{
PSVM(String[]args)
{
DesiredCapabilities capability =DesiredCapabilities.firefox();
String URL=URL;
URL ClientURL=new URL(URL);
RemoteWebDriver driver=new RemoteWebDriver(ClientURL,Capability);
}
}
Q parameteriation
Q Xpath Axis
AxisName Result
ancestor Selects all ancestors (parent,grandparent, etc.) of thecurrent node
ancestor-or-self
Selects all ancestors (parent,grandparent, etc.)of thecurrent node andthecurrent node
itself
attribute Selects all attributes of the current node
child Selects all children of thecurrent node
8
descendant Selects all descendants (children, grandchildren,etc.) ofthe current node
descendant-or-self
Selects all descendants (children, grandchildren,etc.) ofthe current node andthe current
node itself
following Selects everythingin the document afterthe closingtagof thecurrent node
following-sibling Selects all siblings after thecurrent node
namespace Selects all namespace nodes of the current node
parent Selects the parent of the current node
preceding
Selects all nodes that appear before the current node in the document, except ancestors,
attribute nodes andnamespace nodes
preceding-sibling Selects all siblings before the current node
self Selects the current node
child::book
attribute::lang
child::*
attribute::*
child::text()
child::node()
descendant::book
ancestor::book
ancestor-or-
self::book
child::*/child::price
44.Whatis thedifferencebetween absolute path and relativepathwhileusing xpath?
OR What is thedifference between / and // in xpath
Absolute path ( / )will give completeaddress oftheelement whereas relativepath (//) willmatchthenext immediatechild.
45.How to handleupload popups using Selenium?
We could inspect the browsebutton, so weuse sendkeys method todirectly inputthefilelocation for uploading thefile.
46.How to handledownload popups using Selenium?
47.Selenium does not handlewindows outofbrowser sowe need tousethirdparty tools likeAutoITto handledownload popups.
Differencebetween quit() and close()?
Close() closes thebrowserwindowwhich is infocus whereas quit() shuts down theWebDrivers instancemeaning itwill closeall browser
window opened by selenium automation.
48.How to prioritize tests?
We need to usethe‘priority‘parameter,ifyou wantthemethods to beexecutedin order.
OOPs in selenium:
1) ABSTRACTION
In Page Object Model design pattern,we write locators (such as id, name, xpathetc.,)in a Page Class. We utilize these locators in tests but we
can’t see these locators in thetests. Literallywe hide the locators from thetests.
Abstraction is themethodologyof hidingtheimplementationof internal details andshowingthe functionalitytothe users.
2) INTERFACE
Basic statementwe allknow in Seleniumis WebDriver driver =newFirefoxDriver();
WebDriver itselfis an Interface. So basedon the above statement WebDriver driver =new FirefoxDriver(); weareinitializing Firefox browser
using SeleniumWebDriver. Itmeans we arecreating a referencevariable(driver) ofthe interface(WebDriver) and creating anObject. Here
WebDriver is anInterface as mentionedearlier and FirefoxDriver is a class.
3) INHERITANCE
We create a BaseClass in theFramework to initializeWebDriver interface, WebDriver waits, Propertyfiles,Excels, etc., intheBaseClass.
We extendtheBaseClass inother classes suchas Tests and Utility Class. Extending oneclass into other class is known as Inheritance.
4)polymorphism: METHOD OVERLOADING
We use implicit wait inSelenium. Implicitwait is anexampleofoverloading. InImplicit waitweusedifferenttime stamps such as SECONDS,
MINUTES, HOURS etc.,
5) polymorphism: METHOD OVERRIDING
We use a methodwhich was already implementedin another class bychanging its parameters. To understand this, you need tounderstand
Overriding inJava.
Declaring a method inchildclass whichis already present intheparent class is calledMethodOverriding. Examples areget andnavigate
methods of differentdrivers in Selenium.
9
6) ENCAPSULATION
All the classes in a frameworkareanexampleofEncapsulation. InPOMclasses,we declarethedata members using @FindBy andinitialization
of data members will bedone using Constructor toutilize thosein methods.
Encapsulation is a mechanismofbinding codeand data together ina singleunit.
49.. How to takescreenshotusing listeners
public class TestListenerimplements ITestListener{
privateWebDriver driver;
public void onTestFailure(ITestResultresult) {
// since youneed the driver inyourscreenshotmethod do this:
this.driver=((TestBaseClass)result.getInstance()).driver;
// here comes your screenshot method
// ...
}
public void onTestStart(ITestResult result) {
}
public void onTestSuccess(ITestResult result) {
}
public void onTestSkipped(ITestResultresult) {
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
}
public void onStart(ITestContext context) {
}
public void onFinish(ITestContext context) {
}
}
Then in your xmlfilejust addthetestlistener:
<suite name="allSuites">
<suite-files>
<suite-filepath="yourtestsuite01.xml"/>
<suite-filepath="yourtestsuite02.xml"/>
</suite-files>
<listeners>
<listener class-name="drkthng.comparex.TestListener"/>
</listeners>
</suite>
Case 1: Execute failed test casesusing TestNG in Selenium–By using “testng-failed.xml”
Steps
1-If your test cases are failingthenonce all test suite completed then youhave to refresh yourproject . Rightclickon project>Clickon refresh or
Select projectandpress f5.
2-Check test-output folder, atlast, you willget testng-failed.xml
3-Now simply runtestng-failed.xml.
Case 2: Execute failed test casesusing TestNG in Selenium–By Implementing TestNG IRetryAnalyzer.
RetryFailedTestCasesimplementsIRetryAnalyzer:
Create separate Classwhich will implement IRetryAnalyerinterface
package TestNGDemo;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
// implement IRetryAnalyzer interface
public class Retry implements IRetryAnalyzer{
10
// set counter to 0
int minretryCount=0;
// set maxcountervaluethis will executeour test 3 times
int maxretryCount=2;
// overrideretry Method
public boolean retry(ITestResult result) {
// this willrun until maxcount completes iftestpass within this frameit willcomeout offor loop
if(minretryCount<=maxretryCount)
{
// print the testnamefor log purpose
System.out.println("Following test is failing===="+result.getName());
// print the counter value
System.out.println("Retrying thetest Countis==="+(minretryCount+1));
// incrementcounter each timeby 1
minretryCount++;
return true;
}
return false;}}
Now we are done almostonlywe need to specify this in the test case
@Test(retryAnalyzer=Retry.class)
Program to Rerun failedtestcases in selenium
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class VerifyTitle
{
// Here we haveto specify theclass –In our caseclass nameis Retry
@Test(retryAnalyzer=Retry.class)
public void verifySeleniumTitle()
{
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.learn-automation.com");
11
// Here we are verifying that titlecontains QTP or not. This testwill failbecause titledoes not contain QTP
Assert.assertTrue(driver.getTitle().contains("QTP"));
Q50:
@How to find if imageis attherightsideofwebpage
1)WebElement ImageFile=driver.findElement(By.xpath("//img[contains(@id,'TestImage')]"));
2) Boolean ImagePresent =(Boolean) ((JavascriptExecutor)driver).executeScript("returnarguments[0].complete&&typeof
arguments[0].naturalWidth!= "undefined"&&arguments[0].naturalWidth >0", ImageFile);
Q51:Assertion
Q:
Q52:What isListenersin Selenium WebDriver?
Listener is definedas interfacethatmodifies thedefault TestNG's behavior. As thenamesuggests Listeners "listen"to theeventdefined inthe
seleniumscript and behave accordingly.It is usedin seleniumby implementing Listeners Interface. Itallows customizing TestNG reports or logs.
There are many types ofTestNG listeners available.
IReporter, reporting
ITestListener,takescreenshot
IRetryAnalyzerretry failed test case running
i)Listenerclass
public class ListenerTest implements ITestListener
{
@Override
public void onFinish(ITestContext Result)
{
}
ii)In main class
@Listeners(Listener_Demo.ListenerTest.class)
In XML file include
<listeners>
<listener class-name=listenerclass>
</listeners>
Listeners are requiredtogenerate logs or customize TestNGreports in Selenium Webdriver.
There are manytypes of listeners andcanbe usedas per requirements.
Listeners are interfaces usedin selenium webdriver script
Demonstratedthe use of Listener in Selenium
Implementedthe Listeners for multiple classes

Experienced Selenium Interview questions

  • 1.
    0 1) How tohandle ajaxobject/dynamic object. Ans:we canusecontains() function Eg. <input id=’email’type=’email’ /> Xpath : //input[contains(@id,’ema’)] 2) What is webdriverjava interface? Ans: Technically webdriver is a collection ofinterfaces andclass Webdriver is a webbasedautomation testing tool, it uses api todrive the test onthebrowser Webdriver as nativesupport’s almost allthebrowsers 3)How do you identify theobjects? In what scenarios theselocators areused? Ans: Id linktest Name partiallink Xpath tagname Css locatorclassname 4) How to work withbutton which is indiv tag andyou haveto click withoutusing xpath. Ans: using submit() OR using sendkeys(keys.enter) 5)How to pass keyboard operations Ans: wb.sendkey(key.downkey) 6) How to work withweblist@radiobuttonin webdriver. Or howto work with weblist (dropdown) Ans: we createobject ofselect class anduseobjectto select. Eg. Webelement webele=driver.findelement(By.name(“”)); Select select =new Select(webele) select.selectbyvisibletext(“abc”); Thread.sleep(2000); select.selectByvalue(“s”); 7)multiple selectlistbox Ans: webdriverdriver=new firefoxdriver(); Driver.get(“file”); Select sel=newSelect(driver.findelementby( “”)); Sel.selectbyvisibletext(“a”); Sel.selectbyvisibletext(“b”); 8)How to get text from UI. Ans: Come to name (Independentvalue) Sibling (which is dependent ) Then get value ofA intostring Eg. Driver.findelement(by.linktext(“projects abd customer”)).click(); Driver.findelement(by.linktext(“aaa”).click()); String expectedCustname=driver.findelement(by.xpath(“”)); String actcustname=’a’; SOP(actcustname.equals(expectedCustname)); 9)How to handle dynamicdropdown Ans: Eg. WebElementwb=driver.findElement(By.name(“”)); Select selcust=new Select(wb); List<WebElement>custlist=selcust.getOptions(); SOP(custlist.size()); String expectedVal=”abc”; Boolean flag=false; For (int i=0;i<=custlist.size(); i++){ String actualVal=custlist.get(i).getText(); If(expectedVal.equals(actualVal)){ SelCust.SelectByVisibleText(expectedVal);
  • 2.
    1 Flag=true; Break;} If(flag) {sop(“value not indropdown”);}} 10)Howto verifiy colour oftext orimage. Ans: <h1 class=”redtext”>GMAIL</h1> Fetch value ofclass attribute Driver.FindElement(locator).GetAttribute(“class”) 11)How to check which tab is enabled Ans Use GetAttribute 12)Check howmany links presentin UI and click onlink5 suppose. Ans: Webdriverdriver=newFirefoxDriver(); Driver.get(“ ”); Int a =driver.findElement(By.xpath(“”)); List<WebElement>listOfLinks=driver.findElement(By.xpath(“”)); Sop(listOfLinks.size()); String expectedLink =”Switch togmail”; Boolean flag=false; For(int i=0;i<listOfLinks.Size();i++){ String actVal=listOfLink.get(i).getText(); If(expectedLink.equals(actVal)) { Driver.findElement(By.linkText(ExpectedLink).click()); SOP(“link text present”); Flag=true; Break; } If (! flag) { SOP (“link not present”); } 13) Difference between Implicitwaitandexplicitwait. Ans: also fluentwait Implicitwait Explicit wait In Implicit wait, tell’s webdriverto poll thedom{xml,html}document for a certain amountoftimewhentrying to find anelement. Wait tillelementis presentin UI Waits tillpage gets downloaded Generally webdriver waitcheckexpected conditionby every500 milliseconds ifelement found within specified amountof time,webdriver nextstepexecution(notgoing to waitfor entire 10sec) If page gets downloadedwithinspecifiedamount oftime, webdriver dos not wait for specified time, itwill continuethenext step execution. Does not throwanyexception Disadvantage: Ajaxapplication wait doesn’t work Driver.manage().Timeouts().ImplicitWait(10000,TimeUnit.secounds) /.hours/.milisecounds/.days WebdriverWait wait=new WebDriverWait(driver,10); Wait.Until(ExpectedCondition.elementToBeClickable(locator)); 14) How to check whetherbuttonis enabled or not. Ans: driver.findElement(By.name(Username).isEnabled(); .isSelected(); .isDisplayed(); All methods aregoing toreturnBoolean; 15) How to handlewindow popup? Ans: Set<String>WinList1=driver.getWindowHandles();
  • 3.
    2 Iterator<String>it1=WinList1.iterator(); String parentWinId=it1.next(); Stirng ChildWinId=it1.next(); Driver.switchto.Window(ChildWinId); Performactions on child window thenpass controlback toparent window Close current window Driver.close(); Driver.switchto.Window(ParentWinId); Driver.close(); Driver.quit(); When an action calls a pop upto open a new window, webdriverdoes not automatically takecontrol ofthenew popup window.Transfer control to child window. 17) Once we click anylink automatically weget lots ofpop up.How toget the desiredone. Ans: Will haveset ofwindow id’s. Using HasNext() iterateto allthewindowGetTitle() andcheck ifwindow titleis sameas required. 18) How to handlealert? Ans: Alert alt =driver.SwitchTo.alert(); SOP(alt.getText()); Alt.accept(); Alt.dismiss(); 19) How to countno. ofalert present in UI. Ans: int count; Boolean flag=true; While(flag) { Try{ Alert alt=driver.SwitchTo.alert(); Count=count+1; Alt.accept();} Catch(no alert presentexceptione) {Flag=true ;} } 2)How to switch toframe? Ans: find element byiframetag Driver.get(“times ofindia”); Thread.sleep(1000); Driver.switchTo.frame(“id”); Driver.findElement(locator).sendkeys(“10”); 21)What is the useofActions class inwebdriver? OR howto workwith keyboard and mouseoperations? Ans: Mouse actions:(Action classes) movetoElement(); draganddrop(); contextClick(); sendkeys(); Eg. Actions act=new Actions(driver); Act.dragAndDrop(SourceWeb,destination).build().perform(); Actions act =new Actions(driver); Act.sendkeys(keys.Tab,keys.Enter).build.perform(); Move to mousemoment Actions act=new Actions(driver); Act.moveToElement(wb).build().perform(); Driver.findElement(locator).click(); Right click operation Action act=newActions(driver); Act.contextclick(sourceweb).build.perform(); 22)How to handle googlesearch text? OR Autosuggest/Autocompleteeditbox. Ans: driver.get(URL“);
  • 4.
    3 Driver.findElement(By.id(“locator”)).sendkeys(“value”); Driver.findElement(By.xpath(“”)).click(); List<Weblist>str=driver.findElement(By.xpath(“locator”));//capture allthecoming suggestionsand display the list. For(i=0;i<=str.size()-1;i++) { Sop(str.get(i).getText()); } 23)How wouldyou doproxy settings using webdriver. Samoriginpolicy Ans: firefoxProfile profile=newFirefoxprofile(); profile.setpreferences(“network.proxy.type”,1); profile.setpreference(“network.proxy.http”,’localhost”); profile.setpreference(“network.proxy.http_port”,3128); Webdriver driver=new Firefoxdriver(profile); 24)How to work withhttps websiteOR howto handleSSL certificationin Firefox Ans: FirefoxProfileprofile=new firefoxProfile(); FirefoxProfile.SetAssumeUntrustedCertificateIssue(false); Driver=newFirefoxDriver(fireforxprofile); Driver.get(“https://google.com”); 25)Delete system cookies Ans: WebDriverdriver=new FirefoxDriver(); Driver.manage().deleteAllcookies(); 26) How to work with file attachment andfiledownload inwebdriver. AutoIt Ans: 1)if editbox is not disabled wecan attachfileusing sendkeys(); 2)Use AutoIT of edit boxis disabled. #include<IE.au3> $oShell=ObjCreate(“Shell.application”); $oShallWindows =$oshell.windows; WinActive(“FileUpload”);//checkifupload window is active $file=”filepath”; ControlSetText(“File Upload”,”Edit”,$file); ControlClick(“FileUpload”, “Button1”); 3)Convert .au3to .exefile 4)call .exe in eclipse In eclipse PSVM() { Runtime.getRuntime().exec(pathofexefile); } 33)File Upload using sendkeys Ans Public class uploadfiles {public staticvoidmain(Stirng args[]) { FirefoxDriverdriver=newFirefoxDriver(); Driver.get(URL); File file=null; Try { File =new File(path); }Catch(Exception e) { e.printStackTrace(); } Assert.assertTrue(file.exists()); WebElementbrowserbutton=driver.findElement(By.id(“locator”));
  • 5.
    4 browserButton.senkeys(file.getAbsolutePath()); } } 27)How to handlecalender pop up? 28)Read data fromexcel sheet? Ans: Apache OPIlibraries PSVM() { FileinsputStreamfs=new FileInputStream(“”); Workbook ws=WorkbookFatory.Create(fs); Sheet sh=ws.getSheet(“sheet name”); Int rowCount=getRowCount(“Sheet1”); For(int i=1;i<=rowCount;i++) { String testCaseName=sh.getRow(i).getCell(0).getStringCelValue(); TestCaseDsc=sh.getRow(i).getCell(1).getStringCellValue(); } } 29)Write data to Excel sheet Ans: PSVM() { FileInputStreamfs=new FileInputStream(); Workbook wb=WorkbookFactory.Create(fs); Sheet sh=wb.getSheet(“sheetname”); Row rw=sh.getRow(1); Cell cel=rw.createCell(6); Cel.SetCellType(cel.Cell_TYPE_STRING); Cel.setCellValue(“abcd”); FileOutputStreamfos=new FileoutputStream(“”); Fos.write(fos); } 30)Write syntax for finding therow count indynamic webtable Ans: //Function Public HasMap<String.String>getRowData(String xpathRowElement) String row=Driver.findElement(By.xpath(xpathRowElement)).getText(); SOP(row); String[]rowArray=row.Split(“”);//split by space Hashmap<String,String>rowData1=new HashMap<String,String>; rowData1.put(“Customer/projects”,rowArray[0]); rowData1.put(“AddTask/projects”,rowArray[1]+rowArray[2]); return rowData1; } //In test case HashMap<String,String>CustomerRowData=getRowData(“xpath”); If(CustName.equals(CustomerRowData.get(“Customer/projects”))) { SOP(customerrowdata) } String task=”0” If(task.equals(customerRowData.get(Opentask“))) {SOP(customerRowData(“OpenTask”)); } 31)TestNG and Advantages Ans: Testing is a framework usedfor core java unittesting It does not havea UI . It’s a collection of.jar files. TestNG does nothavea mainmethod torun a class whichuses annotations toidentify thetest.
  • 6.
    5 testing executemultiple testcases through TestNG-XMLfileand generateaHTMLreportwithout any manual intervention. 32)TestNG annotations. Ans; @Test @Beforemethod @Aftermethod @BeforeClass @Afterclass @Beforesuite @AfterSuite grouping using @DataProvider Parallelexecution TestNG method should bevoid. Does notreturnanything. One TestNG class canhave multipletest. 33)What arethedifferent arguments arepassed along with @Test annotationin TestNG? Ans: 34)Group executionin TestNG-XLMfile Ans: //Suppose wehave Public class VerifyCustomerField{ @Test(groups={“feature1”,TestCreateCustomer}) Public void verify customer() { SOP (“Test1”); } Public class CustomerandprojectTest{ @Test(groups={“feature1”,TestCustomer&Project}) Public void verify customer&Project() { SOP (“Test2”); } //TestNG-XML looks like <Suite name=”Suite”parallel=”None”> <test name=”Test”> <groups> <run> <include name=”feature1”></include> </run> </groups> //Or another example <classes> <class name=”VerifyCustomerField”> <class name=”CustomerandprojectTest”> </classes> </test> </suit> 35)How to include andexcludethegroups in the testing XMLfile? Ans: <excludename=”groupname”></exclude> 36)How to achieveparallel execution inTestNG. Ans: <Suite name=”Suite”parallel=”tests” preserve-order=”true”> <test name=”Test”preserve-order=”true”> <classes> <class name=”VerifyCustomerField”> <class name=”CustomerandprojectTest”> </classes> </test> </suit>
  • 7.
    6 37)what are thedifferentarguments passedto testing Ans: @Test(dependsOnMethod={“”loginTest}) Public void testCreateCustomer() { SOP(“create cusotmer”); } @Test Public void loginTest() { SOP(“login”); } @Test(dependsOnMethod={“”TestCreateCustomer}) Public void logout() { SOP(“logout”); } 38)parallelexecution Ans: Test in parallel <Suite name=”suite”parallel=”tests”preserve-order=”true”thredcount=”5”> Method in parallel <Suite name=”suite”parallel=”methods” preserve-order=”true” thredcount=”5”> Classes in parallel <Suite name=”suite”parallel=”classes”preserve-order=”true”thredcount=”5”> 45)What arethetypes ofassertions and what areassertions intesting Ans: Eg. If you want to failtestcases: Public class test1 { @Test Public voidloginTest(){ String actualName=”abc”; String expectedname=”ab”; If(actualName.equals(expectedname)) { Assert.assertTrue(true,’Test is pass’); } Else { Assert.assertTrue(false,”Test is fail”); } } 39)Types of assertions Ans: AssertTrue() AssertFalse() AssertEquals() AssertNotEqual() AssertSame() AssertNotSame() AssertNull AssertNotNull Eg: @Test Public void login() { Generic lib=newgenericlib(); Try{ Assert.assertTrue(lib.login(“admin”,”password”),”Customer not matching”); }Catch(Throwablee) { SOP(catch block}} 40) Most commonExceptions:
  • 8.
    7 1) NoSuchElementException :FindBy method can’t find the element. 2) StaleElementReferenceException : This tells that element is no longer appearing on the DOM page. 3) TimeoutException: This tells that the execution is failed because the command did not complete in enough time. 4) ElementNotVisibleException: Throw n to indicate that although an element is present on the DOM, it is not visible, and so is not able to be interacted w ith 5) ElementNotSelectableException: Throw n to indicate that may be the element is disabled, and so is not able to select. 41)How to takescreenshots? Ans: Psvm(String[]args) { WebDriver driver=new FireFoxWebDriver(); Driver.get(weblink); EventFiringWebDriver edriver=new EventFirinfWebDriver(); File srcImg=edriver.getScreenShotAs(OutputType.FILE); File destImg=newFile(file location); FileUtils.copyFilesToDirectory(srcImg,desImg); } 42)Differenceget() and navigate().to(); 43)How to do data parameterization? What is data provider? Ans: To do a parameterization Running sametestscript withmultiple data Test data from excelsheet,or xml sheet. Eg. Public class testNgDataProvider{ @Test(dataProvider=”getData”) Public void checkAccountStatusTest(String accname,String Psw) { SOP(accname); SOP(Psw); } } @DataProvider Public Object[][]getData() { Object[][]data=new Object[5][2]; Data[0][0]=”Act1”; Data[0][1]=”Pass1”; Return data;} 51)What is selenium grid As: Want to runtestscripts on differentmachines, different browsers acts like remotecontrol. Eg. Public class selenium grid{ PSVM(String[]args) { DesiredCapabilities capability =DesiredCapabilities.firefox(); String URL=URL; URL ClientURL=new URL(URL); RemoteWebDriver driver=new RemoteWebDriver(ClientURL,Capability); } } Q parameteriation Q Xpath Axis AxisName Result ancestor Selects all ancestors (parent,grandparent, etc.) of thecurrent node ancestor-or-self Selects all ancestors (parent,grandparent, etc.)of thecurrent node andthecurrent node itself attribute Selects all attributes of the current node child Selects all children of thecurrent node
  • 9.
    8 descendant Selects alldescendants (children, grandchildren,etc.) ofthe current node descendant-or-self Selects all descendants (children, grandchildren,etc.) ofthe current node andthe current node itself following Selects everythingin the document afterthe closingtagof thecurrent node following-sibling Selects all siblings after thecurrent node namespace Selects all namespace nodes of the current node parent Selects the parent of the current node preceding Selects all nodes that appear before the current node in the document, except ancestors, attribute nodes andnamespace nodes preceding-sibling Selects all siblings before the current node self Selects the current node child::book attribute::lang child::* attribute::* child::text() child::node() descendant::book ancestor::book ancestor-or- self::book child::*/child::price 44.Whatis thedifferencebetween absolute path and relativepathwhileusing xpath? OR What is thedifference between / and // in xpath Absolute path ( / )will give completeaddress oftheelement whereas relativepath (//) willmatchthenext immediatechild. 45.How to handleupload popups using Selenium? We could inspect the browsebutton, so weuse sendkeys method todirectly inputthefilelocation for uploading thefile. 46.How to handledownload popups using Selenium? 47.Selenium does not handlewindows outofbrowser sowe need tousethirdparty tools likeAutoITto handledownload popups. Differencebetween quit() and close()? Close() closes thebrowserwindowwhich is infocus whereas quit() shuts down theWebDrivers instancemeaning itwill closeall browser window opened by selenium automation. 48.How to prioritize tests? We need to usethe‘priority‘parameter,ifyou wantthemethods to beexecutedin order. OOPs in selenium: 1) ABSTRACTION In Page Object Model design pattern,we write locators (such as id, name, xpathetc.,)in a Page Class. We utilize these locators in tests but we can’t see these locators in thetests. Literallywe hide the locators from thetests. Abstraction is themethodologyof hidingtheimplementationof internal details andshowingthe functionalitytothe users. 2) INTERFACE Basic statementwe allknow in Seleniumis WebDriver driver =newFirefoxDriver(); WebDriver itselfis an Interface. So basedon the above statement WebDriver driver =new FirefoxDriver(); weareinitializing Firefox browser using SeleniumWebDriver. Itmeans we arecreating a referencevariable(driver) ofthe interface(WebDriver) and creating anObject. Here WebDriver is anInterface as mentionedearlier and FirefoxDriver is a class. 3) INHERITANCE We create a BaseClass in theFramework to initializeWebDriver interface, WebDriver waits, Propertyfiles,Excels, etc., intheBaseClass. We extendtheBaseClass inother classes suchas Tests and Utility Class. Extending oneclass into other class is known as Inheritance. 4)polymorphism: METHOD OVERLOADING We use implicit wait inSelenium. Implicitwait is anexampleofoverloading. InImplicit waitweusedifferenttime stamps such as SECONDS, MINUTES, HOURS etc., 5) polymorphism: METHOD OVERRIDING We use a methodwhich was already implementedin another class bychanging its parameters. To understand this, you need tounderstand Overriding inJava. Declaring a method inchildclass whichis already present intheparent class is calledMethodOverriding. Examples areget andnavigate methods of differentdrivers in Selenium.
  • 10.
    9 6) ENCAPSULATION All theclasses in a frameworkareanexampleofEncapsulation. InPOMclasses,we declarethedata members using @FindBy andinitialization of data members will bedone using Constructor toutilize thosein methods. Encapsulation is a mechanismofbinding codeand data together ina singleunit. 49.. How to takescreenshotusing listeners public class TestListenerimplements ITestListener{ privateWebDriver driver; public void onTestFailure(ITestResultresult) { // since youneed the driver inyourscreenshotmethod do this: this.driver=((TestBaseClass)result.getInstance()).driver; // here comes your screenshot method // ... } public void onTestStart(ITestResult result) { } public void onTestSuccess(ITestResult result) { } public void onTestSkipped(ITestResultresult) { } public void onTestFailedButWithinSuccessPercentage(ITestResult result) { } public void onStart(ITestContext context) { } public void onFinish(ITestContext context) { } } Then in your xmlfilejust addthetestlistener: <suite name="allSuites"> <suite-files> <suite-filepath="yourtestsuite01.xml"/> <suite-filepath="yourtestsuite02.xml"/> </suite-files> <listeners> <listener class-name="drkthng.comparex.TestListener"/> </listeners> </suite> Case 1: Execute failed test casesusing TestNG in Selenium–By using “testng-failed.xml” Steps 1-If your test cases are failingthenonce all test suite completed then youhave to refresh yourproject . Rightclickon project>Clickon refresh or Select projectandpress f5. 2-Check test-output folder, atlast, you willget testng-failed.xml 3-Now simply runtestng-failed.xml. Case 2: Execute failed test casesusing TestNG in Selenium–By Implementing TestNG IRetryAnalyzer. RetryFailedTestCasesimplementsIRetryAnalyzer: Create separate Classwhich will implement IRetryAnalyerinterface package TestNGDemo; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; // implement IRetryAnalyzer interface public class Retry implements IRetryAnalyzer{
  • 11.
    10 // set counterto 0 int minretryCount=0; // set maxcountervaluethis will executeour test 3 times int maxretryCount=2; // overrideretry Method public boolean retry(ITestResult result) { // this willrun until maxcount completes iftestpass within this frameit willcomeout offor loop if(minretryCount<=maxretryCount) { // print the testnamefor log purpose System.out.println("Following test is failing===="+result.getName()); // print the counter value System.out.println("Retrying thetest Countis==="+(minretryCount+1)); // incrementcounter each timeby 1 minretryCount++; return true; } return false;}} Now we are done almostonlywe need to specify this in the test case @Test(retryAnalyzer=Retry.class) Program to Rerun failedtestcases in selenium import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import org.testng.annotations.Test; public class VerifyTitle { // Here we haveto specify theclass –In our caseclass nameis Retry @Test(retryAnalyzer=Retry.class) public void verifySeleniumTitle() { WebDriver driver=new FirefoxDriver(); driver.manage().window().maximize(); driver.get("http://www.learn-automation.com");
  • 12.
    11 // Here weare verifying that titlecontains QTP or not. This testwill failbecause titledoes not contain QTP Assert.assertTrue(driver.getTitle().contains("QTP")); Q50: @How to find if imageis attherightsideofwebpage 1)WebElement ImageFile=driver.findElement(By.xpath("//img[contains(@id,'TestImage')]")); 2) Boolean ImagePresent =(Boolean) ((JavascriptExecutor)driver).executeScript("returnarguments[0].complete&&typeof arguments[0].naturalWidth!= "undefined"&&arguments[0].naturalWidth >0", ImageFile); Q51:Assertion Q: Q52:What isListenersin Selenium WebDriver? Listener is definedas interfacethatmodifies thedefault TestNG's behavior. As thenamesuggests Listeners "listen"to theeventdefined inthe seleniumscript and behave accordingly.It is usedin seleniumby implementing Listeners Interface. Itallows customizing TestNG reports or logs. There are many types ofTestNG listeners available. IReporter, reporting ITestListener,takescreenshot IRetryAnalyzerretry failed test case running i)Listenerclass public class ListenerTest implements ITestListener { @Override public void onFinish(ITestContext Result) { } ii)In main class @Listeners(Listener_Demo.ListenerTest.class) In XML file include <listeners> <listener class-name=listenerclass> </listeners> Listeners are requiredtogenerate logs or customize TestNGreports in Selenium Webdriver. There are manytypes of listeners andcanbe usedas per requirements. Listeners are interfaces usedin selenium webdriver script Demonstratedthe use of Listener in Selenium Implementedthe Listeners for multiple classes