Experienced Selenium Interview questions

A
archana singhSr. Selenium Automation test engineer à E2Open

Selenium interview questions for experienced candidates.

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

Recommandé

Java. Explicit and Implicit Wait. Testing Ajax Applications par
Java. Explicit and Implicit Wait. Testing Ajax ApplicationsJava. Explicit and Implicit Wait. Testing Ajax Applications
Java. Explicit and Implicit Wait. Testing Ajax ApplicationsМарія Русин
931 vues42 diapositives
Learning Java 4 – Swing, SQL, and Security API par
Learning Java 4 – Swing, SQL, and Security APILearning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APIcaswenson
1.7K vues22 diapositives
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing par
BDD, ATDD, Page Objects: The Road to Sustainable Web TestingBDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web TestingJohn Ferguson Smart Limited
3.9K vues53 diapositives
Fun Teaching MongoDB New Tricks par
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
2.5K vues27 diapositives
WebDriver Waits par
WebDriver WaitsWebDriver Waits
WebDriver WaitsYaroslav Pernerovsky
1.9K vues55 diapositives
Implicit and Explicit waits in Selenium WebDriwer, how to. par
Implicit and Explicit waits in Selenium WebDriwer, how to.Implicit and Explicit waits in Selenium WebDriwer, how to.
Implicit and Explicit waits in Selenium WebDriwer, how to.Yaroslav Pernerovsky
1.8K vues33 diapositives

Contenu connexe

Tendances

An introduction to Vue.js par
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.jsTO THE NEW Pvt. Ltd.
380 vues35 diapositives
JJUG CCC 2011 Spring par
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
1.7K vues85 diapositives
Tomcat连接池配置方法V2.1 par
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Zianed Hou
660 vues8 diapositives
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 2019 par
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 201910 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 2019Matt Raible
191 vues65 diapositives
How to execute Automation Testing using Selenium par
How to execute Automation Testing using SeleniumHow to execute Automation Testing using Selenium
How to execute Automation Testing using Seleniumvaluebound
3.5K vues15 diapositives
Amazon Cognito使って認証したい?それならSpring Security使いましょう! par
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Ryosuke Uchitate
17K vues102 diapositives

Tendances(20)

Tomcat连接池配置方法V2.1 par Zianed Hou
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
Zianed Hou660 vues
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 2019 par Matt Raible
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 201910 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 2019
Matt Raible191 vues
How to execute Automation Testing using Selenium par valuebound
How to execute Automation Testing using SeleniumHow to execute Automation Testing using Selenium
How to execute Automation Testing using Selenium
valuebound3.5K vues
Amazon Cognito使って認証したい?それならSpring Security使いましょう! par Ryosuke Uchitate
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Ryosuke Uchitate17K vues
JavaFest. Nanne Baars. Web application security for developers par FestGroup
JavaFest. Nanne Baars. Web application security for developersJavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developers
FestGroup212 vues
Java libraries you can't afford to miss par Andres Almiray
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to miss
Andres Almiray12K vues
What the FUF? par An Doan
What the FUF?What the FUF?
What the FUF?
An Doan918 vues
Demystifying dependency Injection: Dagger and Toothpick par Danny Preussler
Demystifying dependency Injection: Dagger and ToothpickDemystifying dependency Injection: Dagger and Toothpick
Demystifying dependency Injection: Dagger and Toothpick
Danny Preussler3K vues
Introduce about Nodejs - duyetdev.com par Van-Duyet Le
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
Van-Duyet Le868 vues
Basic Tutorial of React for Programmers par David Rodenas
Basic Tutorial of React for ProgrammersBasic Tutorial of React for Programmers
Basic Tutorial of React for Programmers
David Rodenas530 vues
Wicket Security Presentation par mrmean
Wicket Security PresentationWicket Security Presentation
Wicket Security Presentation
mrmean2.3K vues
The report of JavaOne2011 about groovy par Yasuharu Nakano
The report of JavaOne2011 about groovyThe report of JavaOne2011 about groovy
The report of JavaOne2011 about groovy
Yasuharu Nakano5.8K vues
Test driven development (java script & mivascript) par Miva
Test driven development (java script & mivascript)Test driven development (java script & mivascript)
Test driven development (java script & mivascript)
Miva824 vues
Activator and Reactive at Play NYC meetup par Henrik Engström
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
Henrik Engström1.7K vues
Appsec usa2013 js_libinsecurity_stefanodipaola par drewz lin
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaola
drewz lin894 vues

Similaire à Experienced Selenium Interview questions

Selenium interview questions and answers par
Selenium interview questions and answersSelenium interview questions and answers
Selenium interview questions and answerskavinilavuG
331 vues22 diapositives
Web driver training par
Web driver trainingWeb driver training
Web driver trainingDipesh Bhatewara
813 vues29 diapositives
Latest Selenium Interview Questions And Answers.pdf par
Latest Selenium Interview Questions And Answers.pdfLatest Selenium Interview Questions And Answers.pdf
Latest Selenium Interview Questions And Answers.pdfVarsha Rajput
35 vues6 diapositives
Web UI test automation instruments par
Web UI test automation instrumentsWeb UI test automation instruments
Web UI test automation instrumentsArtem Nagornyi
10K vues23 diapositives
Das kannste schon so machen par
Das kannste schon so machenDas kannste schon so machen
Das kannste schon so machenAndré Goliath
712 vues69 diapositives
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020 par
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020Matt Raible
177 vues65 diapositives

Similaire à Experienced Selenium Interview questions(20)

Selenium interview questions and answers par kavinilavuG
Selenium interview questions and answersSelenium interview questions and answers
Selenium interview questions and answers
kavinilavuG331 vues
Latest Selenium Interview Questions And Answers.pdf par Varsha Rajput
Latest Selenium Interview Questions And Answers.pdfLatest Selenium Interview Questions And Answers.pdf
Latest Selenium Interview Questions And Answers.pdf
Varsha Rajput35 vues
Web UI test automation instruments par Artem Nagornyi
Web UI test automation instrumentsWeb UI test automation instruments
Web UI test automation instruments
Artem Nagornyi10K vues
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020 par Matt Raible
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
Matt Raible177 vues
Protractor framework architecture with example par shadabgilani
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
shadabgilani208 vues
Node.js and Selenium Webdriver, a journey from the Java side par Mek Srunyu Stittri
Node.js and Selenium Webdriver, a journey from the Java sideNode.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java side
Mek Srunyu Stittri25.9K vues
Testing Ext JS and Sencha Touch par Mats Bryntse
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
Mats Bryntse8.4K vues
Improving Your Selenium WebDriver Tests - Belgium testing days_2016 par Roy de Kleijn
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Roy de Kleijn343 vues
soft-shake.ch - Hands on Node.js par soft-shake.ch
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
soft-shake.ch2.3K vues
Top100summit 谷歌-scott-improve your automated web application testing par drewz lin
Top100summit  谷歌-scott-improve your automated web application testingTop100summit  谷歌-scott-improve your automated web application testing
Top100summit 谷歌-scott-improve your automated web application testing
drewz lin538 vues
3 Mobile App Dev Problems - Monospace par Frank Krueger
3 Mobile App Dev Problems - Monospace3 Mobile App Dev Problems - Monospace
3 Mobile App Dev Problems - Monospace
Frank Krueger112 vues
An Introduction to Celery par Idan Gazit
An Introduction to CeleryAn Introduction to Celery
An Introduction to Celery
Idan Gazit70.3K vues

Dernier

The Path to DevOps par
The Path to DevOpsThe Path to DevOps
The Path to DevOpsJohn Valentino
5 vues6 diapositives
Quality Engineer: A Day in the Life par
Quality Engineer: A Day in the LifeQuality Engineer: A Day in the Life
Quality Engineer: A Day in the LifeJohn Valentino
6 vues18 diapositives
WebAssembly par
WebAssemblyWebAssembly
WebAssemblyJens Siebert
51 vues18 diapositives
Copilot Prompting Toolkit_All Resources.pdf par
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdfRiccardo Zamana
10 vues4 diapositives
Unleash The Monkeys par
Unleash The MonkeysUnleash The Monkeys
Unleash The MonkeysJacob Duijzer
8 vues28 diapositives
Navigating container technology for enhanced security by Niklas Saari par
Navigating container technology for enhanced security by Niklas SaariNavigating container technology for enhanced security by Niklas Saari
Navigating container technology for enhanced security by Niklas SaariMetosin Oy
14 vues34 diapositives

Dernier(20)

Copilot Prompting Toolkit_All Resources.pdf par Riccardo Zamana
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdf
Riccardo Zamana10 vues
Navigating container technology for enhanced security by Niklas Saari par Metosin Oy
Navigating container technology for enhanced security by Niklas SaariNavigating container technology for enhanced security by Niklas Saari
Navigating container technology for enhanced security by Niklas Saari
Metosin Oy14 vues
JioEngage_Presentation.pptx par admin125455
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptx
admin1254556 vues
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx par animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm15 vues
360 graden fabriek par info33492
360 graden fabriek360 graden fabriek
360 graden fabriek
info33492122 vues
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra... par Marc Müller
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra....NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
Marc Müller40 vues
AI and Ml presentation .pptx par FayazAli87
AI and Ml presentation .pptxAI and Ml presentation .pptx
AI and Ml presentation .pptx
FayazAli8712 vues
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P... par NimaTorabi2
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
NimaTorabi212 vues

Experienced Selenium Interview questions

  • 1. 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);
  • 2. 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();
  • 3. 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“);
  • 4. 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”));
  • 5. 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.
  • 6. 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>
  • 7. 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:
  • 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 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.
  • 10. 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{
  • 11. 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");
  • 12. 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