Selenium Interview
Selenium Interview
wait.until(ExpectedConditions.elementToBeSelected(driver.findElement(By.xpath("")))
);
Q)What is FluentWait
Q)What is thread.sleep ?
sleeping script for fixed time
Q)What is pageLoadTimeout?
>Purpose: Sets the amount of time to wait for a page load to complete before
throwing an error. If the timeout is negative, page loads can be indefinite.
driver.manage().timeouts().pageLoadTimeout(100, SECONDS);
driver.switchTo().window(ids.get(3));
driver.findElement(By.xpath("")).isDisplayed();
driver.close();
driver.switchTo().window(ids.get(2));
driver.close();
driver.switchTo().window(ids.get(0));
Q)How to maximize window
>driver.manage().window().maximize();
action1.build().perform();
action2.sendKeys(Keys.ENTER);
action2.sendKeys(Keys.F6);
Q)How to work with alert/How can we handle web based pop up?
>Alert interface
Alert alert = driver.switchTo().alert();
alert.accept();
alert.dismiss();
driver.findElements(By.tagName("iframe")).size();
driver.switchTo().frame(0);
driver.switchTo().frame("auto");
driver.switchTo().frame(driver.findElement(By.className("")));
select.deselectAll();
select.deselectByIndex(3);
select.deselectByValue("valuseName");
select.deselectByVisibleText("textName");
for Scrolling:-
((JavascriptExecutor)driver).executeScript("scroll(0,400)");
>((JavascriptExecutor)driver).executeScript("document.getElementById('some
id').value='mukesh';");
>((JavascriptExecutor)driver).executeScript("document.getElementById('enter your
element id').click();");
System.out.println(testdata.getProperty("userName"));
Q #133) How to check if a text is highlighted on the page ?
Q) What are the java script function for selenium object location?
//following-sibling
//preceding-sibling
//starts-with()
//ends-with()
//following
//preceding
// contains-//a[contains(text(),'Women']
FileInputStream fis;
XSSFWorkbook workbook;
XSSFSheet sheet;
XSSFRow row;
XSSFCell cell;
fis = new
FileInputStream("/src/main/java/com/automation/fb/data/text.xls");
workbook = new XSSFWorkbook(fis);
row = sheet.getRow(0);
row.getLastCellNum();
row.getLastCellNum();
cell = row.getCell(3);
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
String.valueOf(cell.getNumericCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
String.valueOf(cell.getBooleanCellValue());
}
}
Q #5) What are the testing types that can be supported by Selenium?
Functional Testing
Regression Testing
Assert: Assert command checks whether the given condition is true or false. Let�s
say we assert whether the given element is present on the web page or not. If the
condition is true then the program control will execute the next test step but if
the condition is false, the execution would stop and no further test would be
executed.
Verify: Verify command also checks whether the given condition is true or false.
Irrespective of the condition being true or false, the program execution doesn�t
halts i.e. any failure during verification would not stop the execution and all the
test steps would be executed.
Single Slash �/� � Single slash is used to create Xpath with absolute path i.e. the
xpath would be created to start selection from the document node/start node.
Double Slash �//� � Double slash is used to create Xpath with relative path i.e.
the xpath would be created to start selection from anywhere within the document.
FirefoxDriver
InternetExplorerDriver
ChromeDriver
SafariDriver
OperaDriver
AndroidDriver
IPhoneDriver
HtmlUnitDriver
User can use sendKeys(�String to be entered�) to enter the string in the textbox.
Syntax:
WebElement username = drv.findElement(By.id(�Email�));
// entering username
username.sendKeys(�sth�);
isDisplayed()
isSelected()
isEnabled()
Syntax:
isDisplayed():
booleanbuttonPresence = driver.findElement(By.id(�gbqfba�)).isDisplayed();
isSelected():
booleanbuttonSelected = driver.findElement(By.id(�gbqfba�)).isDisplayed();
isEnabled():
booleansearchIconEnabled = driver.findElement(By.id(�gbqfb�)).isEnabled();
Syntax:
String Text = driver.findElement(By.id(�Text�)).getText();
Sample code:
driver.navigate().back();
navigate().forward() � This command lets the user to navigate to the next web page
with reference to the browser�s history.
Sample code:
driver.navigate().forward();
navigate().refresh() � This command lets the user to refresh the current web page
there by reloading all the web elements.
Sample code:
driver.navigate().refresh();
navigate().to() � This command lets the user to launch a new web browser window and
navigate to the specified URL.
Sample code:
driver.navigate().to(�https://google.com�);
driver.findElement(By.linkText(�Google�)).click();
The command finds the element using link text and then click on that element and
thus the user would be re-directed to the corresponding page.
The above mentioned link can also be accessed by using the following command.
driver.findElement(By.partialLinkText(�Goo�)).click();
findElement(): findElement() is used to find the first element in the current web
page matching to the specified locator value. Take a note that only first matching
element would be fetched.
Syntax:
Syntax:
List <WebElement>elementList =
driver.findElements(By.xpath(�//div[@id=�example�]//ul//li�));
packageTestNG;
importorg.testng.annotations.*;
publicclassSettingPriority {
@Test(priority=0)
publicvoidmethod1() {
}
@Test(priority=1)
publicvoidmethod2() {
}
@Test(priority=2)
publicvoidmethod3() {
}
}
Reusability of code
Maximum coverage
Recovery scenario
Low cost maintenance
Minimal manual intervention
Easy Reporting
Module Based Testing Framework: The framework divides the entire �Application Under
Test� into number of logical and isolated modules. For each module, we create a
separate and independent test script. Thus, when these test scripts taken together
builds a larger test script representing more than one module.
Library Architecture Testing Framework: The basic fundamental behind the framework
is to determine the common steps and group them into functions under a library and
call those functions in the test scripts whenever required.
Data Driven Testing Framework: Data Driven Testing Framework helps the user
segregate the test script logic and the test data from each other. It lets the user
store the test data into an external database. The data is conventionally stored in
�Key-Value� pairs. Thus, the key can be used to access and populate the data within
the test scripts.
Selenium QTP
open source paid
web based app window+web
supports multiple languages only VB script
Designing the tools and tests to run software through takes a lot of manual, human
effort, though there are frameworks and tests ready made for engineers to use. Even
with automated testing, human error is still a factor � tools can be buggy,
inefficient, costly, and sometimes even technologically limited in what kinds of
tests they can run on their own.
Q #54) How do you choose which automation tool is best for your specific scenario?
In order to choose the proper automation testing tool, you must consider:
Q #55) What are the different types of scripting techniques for automation testing?
Test automation scripting techniques include key and data driven techniques,
shared, structured, and linear.
Q #59) How can we get the font size, font colour, font text used for the particular
text on the web page use in the selenium?
By using getCCSValue(�font-size�);
1: driver.manage().deleteAllCookies();
We are using the .bat file in this we used �taskkill� command which work on the cmd
exit
We can use bellow given two functions with XPath to find element using attribute
value from beginning.
contains()
starts-with()
� When we do not have complete knowledge about the web elements HTML properties
� When the values of the attributes are dynamic i.e. changing
� When we would like to create a list of web elements containing same partial
attribute value
BY Attributes:
driver.findElement(By.xpath(�//input[contains(@name,�user_name�)]�)).sendKeys(�admi
n�);
By Text():
driver.findElement(By.xpath(�//a[contains(text(), �Marketing�)]�)).click();
<a href=�index.php?module=Campaigns&action=index&parenttab=Marketing�>Marketing</a>
Starts-with()
starts-with() method is used when we know about the initial partial attribute value
or initial partial text associated with the web element. User can also use this
method to locate web elements those are consist of both the static(initial) and
dynamic(trailing) values.
By Attribute
� //a[starts-with(@id,�link-si�)]
� //a[starts-with(@id,�link-sign�)]
Q #73) My Firefox browser Is not Installed at usual place. How can I tell
FirefoxDriver to use It?
If Firefox browsers Is Installed at some different place than the usual place then
you needs to provide the actual path of Firefox.exe file as bellow.
System.setProperty(�webdriver.firefox.bin�,�C:\\Program Files\\Mozilla
Firefox\\Firefox.exe�);
Q #75) Can we run testNG class code without using any TestNg annotation?
Q #78) Describe the differences between JUnit and TestNG unit testing frameworks.
-TestNG support group test @Test(group ={sanity})
TestNG support
Extra Annotations @BeforeTest, @AfterTest,@BeforeSuite, @AfterSuite,@BeforeGroups,
@AfterGroups which are not supported in JUnit.
Q #83) I have a test case with two @Test methods. I want to exclude one @Test
method from execution. Can I do It? How?
>@Test(enabled=false)
>
<classes>
<class name="Your Test Class Name">
<methods>
<exclude name="Your Test Method Name To Exclude"/>
</methods>
</class>
</classes>
<test>
<suite>
<class>
</methods>
</classes>
<suite>
<test>
</classes>
<class>
</methods>
Q #87) Tell me any 5 assertions of TestNG which we can use In selenium webdriver
Assert.assertEquals(actual, expected);
assertTrue
assertFalse
Using TestNG soft assertion, We can continue our test execution even if assertion
fails. That means on failure of soft assertion, remaining part of @Test method will
be executed and assertion failure will be reportedat the end of @Test method.
use submit() method but it can be used only when attribute type=submit.
Q #89) How to write regular expression In testng.xml file to search @Test methods
containing �product� keyword.
<methods>
<include name=�.*product.*�/>
</methods>
<test name="FirefoxTest">
<classes>
</classes>
</test>
<test name="ChromeTest">
<classes>
</classes>
</suite>
Dependency Is very good feature of testng using which we can set test method as
dependent test method of any other single or multiple or group of test methods.
That means depends-on method will be executed first and then dependent test method
will be executed. If depends-on test method will fail then execution of dependent
test method will be skipped automatically. TestNG dependency feature will works
only If depends-on test method Is part of same class or part of Inherited base
class.
public class Dependent {
@Test
Q #95) Can we use implicitly wait() and explicitly wait() together in the test
case?
@DataProvider(name = "Authentication")
// Here we are calling the Data Provider object with its Name
@Test(dataProvider = "Authentication")
driver.findElement(By.id("log")).sendKeys(sUsername);
driver.findElement(By.id("pwd")).sendKeys(sPassword);
First find all the windows handle and then save it in the Iterator and then check
the url of every windows and then switch.
Both methods are abstract method of WebDriver interface and used to find the
WebElement in a web page.
findElement() � it used to find the one web element. It return only one WebElement
type.
findElements()- it used to find more than one web element. It return List of
WebElements.
getOptions() is used to get the selected option from the dropdown list.
It is used to deselect all the options which have been selected from the
dropdown list.
SearchContext.
getWindowHandles()- is used to get the address of all the open browser and its
return type is Iterator<String>.
getWindowHandle()- is used to get the address of the current browser where the
conrol is and return type is String.
use the locator By.tagName and find the elements for the tag //a then use loop to
count the number of elements found.
Syntax- int count = 0;
List<webElement> link = driver.findElements(By.tagName(�a�));
System.out.println(link.size()); // this will print the number of links in a page.
Q #169) What is the difference between thread.Sleep() and selenium. Set Speed
(�2000�)?
If the application is taking time to refresh the page, then we use Thread. Sleep
( ).it is a standard wait it simply wait to the given time.
selenium.setSpeed
Runs each command in after setSpeed delay by the number of milliseconds mentioned
in set Speed.
thread.sleep
Example
It is the directory where reports are generated. Every time tests run in a suite,
TestNG creates index.html and other files in the output directory.
Then it will return List of frames then switch to each and every frame and search
for
the locator which you want then break the loop.
Selenium is an automation testing tool which supports only web application testing.
Therefore, windows pop up cannot be handled using Selenium.
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Some times while doing testing with selenium, we get stuck by some interruptions
like a window based pop up. But selenium fails to handle this as it has support for
only web based application. To overcome this problem we need to use AutoIT along
with selenium script. AutoIT is a third party tool to handle window based
applications. The scripting language used is in VBScript.
Q #172) What is the basic use of Firefox profiles and how can we use them using
selenium?
You have to download AUTO IT.exe file and has to be install and later you have
create .au3 file (in this file you have to specify the commands in
VB script like your file name, where have to save, it will be easy may be 3 or 4
steps )
using AUTOIT�then right click the .au3 file you have to compile �.after that you
will
get the .exe file with the name of .au3 file ..In eclipse you will give the code
like this
Code
<>
if(!result.isSuccess())
{
String userDir = System.getProperty("user.dir");
String customDir = "\\screenshots\\";
String screenShotName = userDir+customDir+new SimpleDateFormat("MM-DD-YYYY-HH-
MM").format(new GregorianCalendar().getTime())
+"-"+result.getMethod().getMethodName()+ ".png";
// Code to capture the screenshot
File srcFile =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try
{
// Code to copy the screenshot in the desired location
FileUtils.copyFile(srcFile,new File(screenShotName));
Reading:-
// load file
FileInputStream fis=new FileInputStream(src);
// Load workbook
XSSFWorkbook wb=new XSSFWorkbook(fis);
-----------------------------------------------------------------------------------
--------------------------------------------------
CUCUMBER BDD
3> Create a stepdefinations package and write corresponding steps defination class
to test class
Copy all the the methods from console and write and now we will write actaul coding
here only
-----------------------------------------------------------------------------------
---------------
Xpath example :
//a[@class='quick-view-mobile']/ancestor::div[@class='quick-view-wrapper-
mobile']/preceding-sibling::a[@class='product_img_link']