Selenium Experienced Level Advanced Interview Questions And Answers
Automation Testing Lifecycle?
Requirement Gathering
Analysis
Designing
Development
Testing
Maintenance
What is Selenium?
Selenium is Open source tool.
Selenium supports to automate the web applications.
Selenium is a suite of Software tools. It is a not a single tool. With the help of other third-party tools will build a selenium framework.
It will support various browsers
It will support various Languages
It will support various operating Systems.
List out the Selenium Components?
IDE – Selenium Integrated Development Environment
RC- Selenium Remote Control
WebDriver
Selenium Grid
Difference between Selenium & QTP?
Selenium QTP
Open Source Paid
More Add-Ons we can use Limited add-ons Only
It will support multiple browsers It will support only Firefox, Chrome, IE
Supports different OS It will support only Windows
It will support Mobile Devices QTP Supports Mobile app test automation (iOS & Android) using HP solution called – HP Mobile Center
Can execute tests while the browser is minimized Not Possible here
Can execute tests in parallel. Can only execute in parallel but using Quality Center which is again a paid product.
What are all the collections concepts mainly will use in selenium?
List
Set
What is the difference between verification and validation?
Verification: Are we building the application or not – to verify this approach is called as “Verification”.
Validation: Are we building the right application or not – to verify this approach is called as “Validation”.
What are all the Testing types we can able to perform using with Automation Testing tool?
Functional Testing: Functional testing is performed using the functional specification provided by the client and verifies the system against the functional requirements.
Ex: All keyboard keys are working properly or not.
Regression Testing: New functionality changes should not affect the existing functionality.
Advantages of Automation Framework?
Reusability of code
Maximum coverage
Recovery scenario
Low-cost maintenance
Minimal manual intervention
Easy Reporting
How to handle Alerts in Selenium?
Will use switchTo() method. Please check the below scenarios.
void dismiss() // To click on the ‘Cancel’ button of the alert.
driver.switchTo().alert().dismiss();
void accept() // To click on the ‘OK’ button of the alert.
driver.switchTo().alert().accept();
String getText() // To capture the alert message.
driver.switchTo().alert().getText();
void sendKeys(String stringToSend) // To send some data to alert box.
driver.switchTo().alert().sendKeys(“Text”);
Explain about Framework using in your project?
You need to clearly explain the following steps:
First, you need to answer why you selected this framework.
How you are maintaining your test suites /cases.
Passing of test data to your test suite/test cases.
Object repository.
Test case execution.
Library folders.
Log files generation.
Test report generation.
Configuration files.
Interviewer cross verifies you by asking versions you are using, we should be ready to answer it.
What is TestNG Data Provider? Write a Syntax for it?
@Test method receives data from this DataProvider. dataProvider name equals to the name of this annotation.
Syntax : @DataProvider(name = “DataProvidename”)
How you will get the title of the page?
driver.getTtile();
How you will get the current URL of the page?
driver.getCurrentUrl();
How to achieve synchronization process in Selenium WebDriver?
Unconditional Synchronization
– Thread.sleep();
Conditional Synchronization
– Implicit Wait
– Explicit Wait
How to handle hidden elements in Selenium WebDriver?
There is no method defined in WebDriver to handle hidden elements and hence we can not handle hidden elements in Selenium.
But through Javascript we can achieve the same.
Syntax:
JavascriptExecutor jsx=((JavascriptExecutor) driver);
jsx.executeScript(“document.getElementsByClassName(element).click();”);
List some scenarios which we cannot automate using Selenium WebDriver?
Bitmap comparison Is not possible using Selenium WebDriver
Automating Captcha is not possible using Selenium WebDriver
We can not read barcode using Selenium WebDriver
We can not automate OTP
How to Upload a file in Selenium WebDriver?
We can Upload a file in Selenium WebDriver directly by passing the Path of the file as an argument to the sendKeys() if the element contains “type=file” in the source code.
Syntax:
driver.findElement(By.xapth(“//div[@type=’file’]”)).sendKeys(“C://Downloads/Resume.html”);
If the element does not contains “type=file” in the source code then uploading a file in Selenium WebDriver can be handled by using Robot class or AutoIT.
How to set test case priority in TestNG?
We can set test case priority in TestNG by using priority attribute to the @Test annotations.
Example:
@Test(priority=2)
public void m1(){
System.out.println(“This is m1 method”);
}
@Test(priority=1)
public void m2(){
System.out.println(“This is m2 method”);
}
Output:
This is m2 method
This is m1 method
What is the default port used by Hub in Selenium Grid?
The default port used by the hub is 4444
How do u get the width of the textbox?
driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getWidth();
driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getHeight();
Is WebElement an interface or a class ?
WebElement is an Interface.
What is the default port used by Node in Selenium Grid?
The default port used by the Node is 5555
What are all the Wait conditions in Selenium? Difference between implicitly Wait, Explicitly Wait and Fluent Wait?
Implicit Wait:
Selenium Web Driver has borrowed the idea of implicit waits from Watir.
The implicit wait will tell to the web driver to wait for certain amount of time before it throws a “No Such Element Exception”.
The default setting is 0. Once we set the time, web driver will wait for that time before throwing an exception.
It is for Page Level.
Syntax:
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
Explicit Wait:
This wait method for Element level.
The explicit wait is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or the maximum time exceeded before throwing an “ElementNotVisibleException” exception.
The explicit wait is an intelligent kind of wait, but it can be applied only for specified elements.
Explicit wait gives better options than that of an implicit wait as it will wait for dynamically loaded Ajax elements.
Syntax:
WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
Fluent Wait uses two parameters – timeout value and polling frequency.
First of all, it sets the following values.
1- The maximum amount of time to wait for a condition, and
2- The frequency to check the success or failure of a specified condition.
Also, if you want to configure the wait to ignore exceptions such as <NoSuchElementException>
Syntax :
Wait wait = new FluentWait(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id(“foo”));
}
});
Step By Step Analysis Of The Above Sample Code.
Step-1: Fluent Wait starts with capturing the start time to determine delay.
Step-2: Fluent Wait then checks the condition defined in the until() method.
Step-3: If the condition fails, Fluent Wait makes the application to wait as per the value set by the <pollingEvery(5, SECONDS)> method call. Here in this example, it’s 5 seconds.
Step-4: After the wait defined in Step 3 expires, start time is checked against the current time. If the difference of the wait start time (set in step-1) and the current time is less than the time set in <withTimeout(30, SECONDS)> method, then Step-2 will need to repeat.
The above steps will recur until either the timeout expires or the condition becomes true.
How to Handle 2 Frames?
to switchto a frame:
driver.switchTo.frame(“Frame_ID”);
to switch to the default again.(parent)
driver.switchTo().defaultContent();
Explain About Maven concept?
Maven simplifies the code handling and process of building the project. Most of the projects follow maven structure.
Download all dependencies provided the dependencies are available in maven central repository. If any of the dependency is not available in maven central repository then you have to add repository path in pom.xml explicitly.
There are many other build tools available in like ant. But it is better to use maven while dealing with different versions and different dependencies. Maven even can manage the dependencies of dependencies. Other tools may not provide such flexibility like maven
Why Jenkins and Selenium?
Running Selenium tests in Jenkins allows you to run your tests every time your software changes and deploy the software to a new environment when the tests pass.
Jenkins can schedule your tests to run at specific time.
You can save the execution history and Test Reports.
Jenkins supports Maven for building and testing a project in continuous integration.
How to capture the color of Web Element or text color in WebDriver?
You can get the element color(Background color of element) by:
element.getCssValue(“background-color”);
You can get the element text/caption color by:
element.getCssValue(“color”);
How to handle 2 windows or explain window handling.
driver.getWindowHandle(); – Single Window
driver.getWindowHandles(); – Multiple windows
Difference between ANT and MAVEN?
Ant Maven
Ant doesn’t has formal conventions, so we need to provide information of the project structure in build.xml file. Maven has a convention to place source code, compiled code etc. So we don’t need to provide information about the project structure in pom.xml file.
Ant is procedural. You need to provide information about what to do and when to do through code. You need to provide order. Maven is declarative, everything you define in the pom.xml file.
There is no life cycle in Ant. There is life cycle in Maven.
It is a tool box. It is a framework.
It is mainly a build tool. It is mainly a project management tool.
The ant scripts are not reusable. The maven plugins are reusable.
It is less preferred than Maven. It is more preferred than Ant.
What is latest version of Selenium WebDriver?
3.11
How to Upload the file in selenium?
Using with SendKeys
RobotClass
AutoIT
List out some TestNG Annotations.?
@BeforeSuite – Before Suite will always execute prior to all annotations or tests in the suite.
@BeforeTest – Before Test will always execute prior to Before Class, ,Before Method and Test Method
@BeforeClass – Before Class will always execute prior to Before Method and Test Method
@BeforeMethod – Before Method will execute before every test method
@AfterMethod – After Method will execute after every test method
@AfterClass – After Class will always execute later to After Method and Test method
@AfterTest – After Test will always execute later to After Method, After Class
@AfterSuite – After suite will always execute at last when all the annotations or test in the suite have run
@Test – Mandatory annotation.
How you will share your output to managers?
TestNG – Emailable Report or XSLT Report.
How to merge all your team members’ code and how you will run?
Git Repository or SVN
How to read and Write the Data from Excel Sheet?
Read Excel Data : FileInputStream.
Write Excel data : FileOutStream
What is the difference between xpath and css selector?
CSS selectors perform far better than Xpath. Majorly in IE Browser.
Xpath : powerful selection of the DOM
CSS : looks simpler. consistent support across browsers
XPATH: no native support for xpath in IE (WebDriver uses a 3rd party library)
CSS: Tests may need to be updated with UI changes
Xpath engines are different in each browser, hence make them inconsistent
IE does not have a native xpath engine, therefore selenium injects its own xpath engine for compatibility of its API. Hence we lose the advantage of using native browser features that WebDriver inherently promotes.
Xpath tend to become complex and hence make hard to read
Explain Testng.xml structure. ( Suite-> Test> Classes>Class)?
Example:
<?xml version=”1.0″ encoding=”UTF-8″?>
<suite name=”example suite 1″ verbose=”1″ >
<test name=”Regression suite 1″ >
<classes>
<class name=”com.first.example.demoOne”/>
<class name=”com.first.example.demoTwo”/>
<class name=”com.second.example.demoThree”/>
</classes>
</test>
</suite>
We need to specify the class names along with packages in between the classes’ tags.
What are all the challenges you have faced while doing the Automation.?
Dealing with pop-up windows:
Selenium can sometimes fail to record common popups in web apps. To handle any kind of alert popup, you can apply a getAlert function. Before actually running the script, you must import a package that can generate a WebDriver script for handling alerts. The efficient interface brings with it the following commands: void dismiss(), void accept (), getText(), void sendKeys(String stringToSend). The first two basically click on the “cancel” and “OK” buttons respectively on a popup window.
No event trigger from value changes:
Because Selenium does not initiate events with a change in values, one must do it oneself using fireEvent: selenium.FireEvent(cmbCategory, “onchange”);
Timeout resulting from synchronization problems:
One should ideally use selenium.IsElementPresent(locator) to verify that the object is in a loop with Thread.Sleep
Testing Flash apps:
To automate flash apps with Selenium, one can use Flex Monkium. The application source code must be compiled with the swc files generated by Flex Monkium. Then the app and the Selenium IDE are connected, and the tests can be recorded with IDE.
Unexpected error launching Internet Explorer. Browser zoom level should be set to 100% by default for the IE browser to overcome this error.
Protected Mode must be set to the same value error occurs when trying to run Selenium WebDriver on a fresh Windows machine. This issue can be fixed by using capabilities as below when launching IE.
What are Exception and Error? Specify the Difference.?
Exception: Exception occurs in the programmer’s code .which can be handled and resolvable.
Ex: arithmetic exception
DivideByZeroException
NullPointerException
ClassNotFoundException
Error: Errors are not resolvable by the programmer. Error occurs due to lack of system resources.
Ex: Stack overflow
hardware error
JVM error
Why Exception Handling important in Selenium?
To continue the flow of execution.
Most Common Exceptions Which We Notice In Selenium WebDriver?
NoSuchElementException: An element could not be located on the page using the given search parameters.
NoSuchFrameException: A request to switch to a frame could not be satisfied because the frame could not be found.
StaleElementReferenceException: An element command failed because the referenced element is no longer attached to the DOM.
Firefox Not Connected Exception: Firefox browser upgraded to new version.
ElementIsNotSelectable Exception: An attempt was made to select an element that cannot be selected.
unknown command Exception: The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource.
ElementNotVisible Exception: An element command could not be completed because the element is not visible on the page.
InvalidElementState Exception: An element command could not be completed because the element is in an invalid state (e.g. attempting to click a disabled element).
UnknownError Exception: An unknown server-side error occurred while processing the command.
javascript error Exception: An error occurred while executing JavaScript code.
XPathLookupError Exception: An error occurred while searching for an element by XPath.
Timeout Exception: An operation did not complete before its timeout expired.
NoSuchWindow Exception: A request to switch to a different window could not be satisfied because the window could not be found.
InvalidCookieDomain Exception: An illegal attempt was made to set a cookie under a different domain than the current page.
UnableToSetCookie Exception: A request to set a cookie’s value could not be satisfied.
UnexpectedAlertOpen Exception: A modal dialog was open, blocking this operation
NoAlertOpenError Exception: An attempt was made to operate on a modal dialog when one was not open.
ScriptTimeout Exception: A script did not complete before its timeout expired.
InvalidElementCoordinates Exception: The coordinates provided to an interactions operation are invalid.
InvalidSelector Exception: Argument was an invalid selector (e.g. XPath/CSS).
Explain the difference between Absolute XPath and relative XPath?
Types of X-path
There are two types of XPath:
1) Absolute XPath.
2) Relative XPath.
Absolute XPath:
It is the direct way to find the element.
It will start with the single forward slash(/) – which means you can select the element from the root node.
Ex : html/body/div[1]/section/div[1]/div/div/div/div[1]/div/div/div/div/div[3]/div[1]/div/h4[1]/b
Disadvantage:
If there are any changes made in the path of the element then that XPath gets failed.
Relative XPath:
It will starts from the middle of the HTML. It starts with the double forward slash (//).
It which means it can search the element anywhere on the webpage.
Ex : //*[@class=’featured-box’]//*[text()=’Testing’]
How to Priority your tests in TestNG?
Ex: @Test (priority=1)
16. How to handle Ajax calls?
AJAX allows the Web page to retrieve small amounts of data from the server without reloading the entire page.
To test Ajax application, different wait methods should be applied
ThreadSleep
Implicit Wait
Explicit Wait
WebdriverWait
Fluent Wait
How to handle Ajax calls?
AJAX allows the Web page to retrieve small amounts of data from the server without reloading the entire page.
To test Ajax application, different wait methods should be applied
ThreadSleep
Implicit Wait
Explicit Wait
WebdriverWait
Fluent Wait
How do you execute your framework from command prompt?
Home-directory > java org,testng.TestNG testng.xml testng2.xml testng2.xml and hit enter
Difference between WebDriver Listener and TestNG listener.
TestNG and Web driver Listener have different interfaces to implement and call them.
WebDriver Event Listener is to listen the events triggered by web driver like beforeClickOn, afterClickOn, beforeFindBy, afterFindBy, etc. and take actions. It is mainly used to write log file for selenium test execution.
TestNG listener mainly used to generate the report for the test. Also, you can capture screenshot when there is test failure. TestNG events are like onTestFailure, onTestSkipped, onTestSuccess, etc.
How you will find the row count and column Count in dynamic web table?
Rows: List<WebElement> rows=htmltable.findElements(By.tagName(“tr”));
Col: List<WebElement> columns=rows.get(rnum).findElements(By.tagName(“th”));
WebDriver is interface or class?
WebDriver is interface
Firefox Browser is interface or class?
FirefoxDriver is Class
Syntax to declare chrome browser and Gecko driver and Firefox Browser and IE browser?
Gecko Driver :
System.setProperty(“webdriver.gecko.marionette”, “Path Of Exe”);
WebDriver driver = new FirefoxDriver();
Chrome Driver:
System.setProperty(“webdriver.chrome.driver”,”Path of Exe”);
//create chrome instance
WebDriver driver = new ChromeDriver();
IE Driver :
System.setProperty(“webdriver.ie.driver”,”Path of Exe “);
//create IE instance
WebDriver driver = new InternetExplorerDriver();
Write a Syntax for Drag and Drop?
Actions act = new Actions(driver);
WebElement From = driver.findElement(By.id(“draggable”));
WebElement To = driver.findElement(By.id(“droppable”));
act.dragAndDrop(From, To).build().perform();
Write Syntax for Mouse Hover Element?
Actions act = new Actions(driver);
action.moveToElement(element).build().perform()
Write Syntax for Double Click?
Actions act = new Actions(driver);
action.doubleClick(element).build().perform();
Write Syntax for Right Click?
Actions act = new Actions(driver);
action.contextClick(element).build().perform();
Difference between Apache POI and Jxl jar files?
JExcel Apache POI
It doesn’t support Excel 2007 and Xlsx format. It supports only Excel 2003 and .Xls format It supports both
JXL doesn’t support Conditional formatting It supports
JXL API was last updated in 2009 Apache POI is actively maintained
It doesn’t support rich text formatting Apache POI supports it
It has very less documents and examples as compare to Apache POI It has extensive set of documents and examples
What are all the element locators in Selenium?
Id
Name
CSSSelector
Xpath
Tagname
ClassName
LinkText
Partial LinkText
How to Handle Dropdown Values in selenium. Write a syntax and types to handle the dropdpwn Box?
Using with Select Class
Syntax:
Select sel = new Select(driver.findElement(By.id(“test”));
Sel.SelectByVisibleText(“value”);
Sel.SelectByValue(“2”);
Sel.SelectByIndex(4);
When will you get element not clickable exception in Selenium?
The reason for the element is not clickable at point(x,y) exception.
Some of my observation was
It mostly happens in Chrome so if you are mostly working with Firefox or IE then you will not be getting this exception.
Chrome does not calculate the exact location of element
Chrome always click in the middle of Element.
Sometimes you will get this exception due to Sync issue also.
How to solve Not connected Exception – unable to connect to host in selenium webdriver?
Scripts that worked earlier may be till yesterday are NOW not working because of Firefox browser upgraded to new version.
Most of them have faced the similar problem when the browser has updated to version. This is the first issue user notices when there is an update in the Firefox browser and may not support selenium with the older version of jars.
If you already have the latest version of selenium, then you have to degrade your browser until there is an update from selenium.
Problem :
Webdriver will just initiate the browser, prompting for a search or address and that ends there with an exception:
org.openqa.selenium.firefox.NotConnectedException:
What is Selenium?
Selenium is a Suite (group) of tools i.e., Selenium IDE, Selenium WebDriver and Selenium Grid to automate web browsers across many platforms.
What is Selenium IDE, WebDriver, and Grid?
Selenium IDE: It is a Firefox plugin which is used to Record and Play the Test Scripts.
Selenium WebDriver: It is a tool which provides an API (that can be understood easily) to automate web browsers with the help of programming languages like Java, Csharp, Python, PHP, Perl, Ruby, and JavaScript.
Selenium Grid: It transparently distributes tests into Remote machines. That is, running multiple tests at the same time against different machines running different browsers and operating systems.
What are the locators available in WebDriver?
Locators: Locators are used to identifying or locate an element (text box, radio buttons, links, check boxes, drop downs, images, text etc. ) in the web page.
Webdriver supports 8 locators i.e., Id, Name, Class Name, Link Text, Partial Link Text, XPath, CSS and Tag Name.
Note: Id is the fastest locator among this 8 locators.
How to launch Firefox, Chrome, IE browser using WebDriver?
The following syntax can be used to launch Browser:
WebDriver driver = new FirefoxDriver();
WebDriver driver = new ChromeDriver();
WebDriver driver = new InternetExplorerDriver();
How to set System Property in WebDriver?
We can set the system property by using setProperty() method, which is a static method defined in System class for which we need to pass 2 parameters i.e., driver name and path of the executable file of the driver.
For Example Setting system property to launch chrome browser
public class ChromeBrowser {
WebDriver driver;
public static void main(String[] args) {
System.setProperty(“webdriver.chrome.driver”, “E://chromedriver.exe”);
driver = new ChromeDriver();
driver.get(“http://www.google.com”);
}
}
How to find font color of Text element?
By using getCssvalue()
For example:
driver.findElement(By.id(“text”)).getCssValue(“color”);
How to find size of the Image?
By using getSize()
How to find Dynamic Web Elements?
We can Dynamic web elements with the help of XPath or CSS.
For Example:
By using XPath:
driver.findElement(By.xpath(“//div[contains(@id,’yui_’)]”));
By using CSS:
driver.findElement(By.cssSelector(“div[id*=’yui_’)]”));
How to skip a test case in JUnit?
By using @Ignore annotation
@Ignore
@Test
public void testDemo(){
System.out.println(“This is testDemo Method”);
}
@Test
public void testPractice(){
System.out.println(“This is testPractice Method”);
}
Output:
This is testPractice Method
Note: Execution in JUnit is carried out in Alphabetical Order
Which is more preferable xpath or CSS?
CSS Selector
How to find out all the links in webpage?
List<WebElement> allLinks = driver.findElements(By.tagName(“a”));
How we will configure the Parallel browser testing in testng.xml?
<suite name=”Parallel test suite” parallel=”tests”>
Explain about TestNG – its listeners?
ITestListener has following methods
OnStart – OnStart method is called when any Test starts.
onTestSuccess– onTestSuccess method is called on the success of any Test.
on test failure– on test failure method is called on the failure of any Test.
onTestSkipped – onTestSkipped method is called on skipped of any Test.
onTestFailedButWithinSuccessPercentage – method is called each time Test fails but is within success percentage.
onFinish – onFinish method is called after all Tests are executed
Write a Syntax to take the screenshot?
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//The below method will save the screen shot in d drive with name “screenshot.png”
FileUtils.copyFile(scrFile, new File(“D:\\screenshot.png”));
How to find out all the frames in a webpage?
List<WebElement> ele = driver.findElements(By.tagName(“frame”));
System.out.println(“Number of frames in a page :” + ele.size());
How to handle cookies?
In Selenium Webdriver interact with cookies with below built-in methods
driver.manage().getCookies(); // Return The List of all Cookies
driver.manage().getCookieNamed(arg0); //Return specific cookie according to name
driver.manage().addCookie(arg0); //Create and add the cookie
driver.manage().deleteCookie(arg0); // Delete specific cookie
driver.manage().deleteCookieNamed(arg0); // Delete specific cookie according Name
driver.manage().deleteAllCookies(); // Delete all cookies
What is Selenium Grid?
Selenium Grid is a tool used together with Selenium RC to run parallel tests across different machines and different browsers all at the same time. Parallel execution means running multiple tests at once.
Features:
Enables simultaneous running of tests in multiple browsers and environments.
Saves time enormously.
Utilizes the hub-and-nodes concept. The hub acts as a central source of Selenium commands to each node connected to it.
Difference between find elements and find element?
FINDELEMENT() METHOD:
FindElement method is used to access a single web element on a page. It returns the first matching element. It throws a NoSuchElementException exception when it fails to find If the element.
Syntax:
driver.findElement(By.xpath(“Value of Xpath”));
FINDELEMENTS() METHOD:
FindElements method returns the list of all matching elements. The findElement method throws a NoSuchElementException exception when the element is not available on the page. Whereas, the findElements method returns an empty list when the element is not available or doesn’t exist on the page. It doesn’t throw NoSuchElementException.
Syntax:
List link = driver.findElements(By.xpath(“Value of Xpath”));
Explain about softAssert and HardAssert?
Asserts are used to perform validations in the test scripts.
There are two types of Assert:
Hard Assert
Soft Assert
When an assert fails the test script stops execution unless handled in some form. We call general assert as Hard Assert.
Hard Assert – Hard Assert throws an AssertExceptionimmediately when an assert statement fails and test suite continues with next @Test.
The disadvantage of Hard Assert – It marks method as fail if assert condition gets failed and the remaining statements inside the method will be aborted.
To overcome this we need to use Soft Assert. Let’s see what is Soft Assert.
Soft Assert – Soft Assert collects errors during @Test. Soft Assert does not throw an exception when an assert fails and would continue with the next step after the assert statement.
If there is any exception and you want to throw it then you need to use assertAll() method as a last statement in the @Test and test suite again continue with next @Test as it is.
We need to create an object to use Soft Assert which is not needed in Hard Assert.
How to Start Jenkins in command Promt?
D:\>Java –jar Jenkins.war
What is the latest version of Jenkins?
Jenkins 2.114
What is Page Object Model?
Page Object Model Framework has now a days become very popular test automation framework in the industry and many companies are using it because of its easy test maintenance and reduces the duplication of code.
The main advantage of Page Object Model is that if the UI changes for any page, it don’t require us to change any tests, we just need to change only the code within the page objects (Only at one place).
The Page Object model provides the following advantages.
There is clean separation between test code and page specific code such as locators (or their use if you’re using a UI map) and layout.
There is single repository for the services or operations offered by the page rather than having these services scattered throughout the tests.
What is the default port for selenium Grid?
The default port used by the hub is 4444
Selenium advantages and disadvantages?
Advantages:
Selenium is pure open source, freeware and portable tool.
Selenium supports variety of languages that include Java, Perl, Python, C#, Ruby, Groovy, Java Script, and VB Script. etc.
Selenium supports many operating systems like Windows, Macintosh, Linux, Unix etc.
Selenium supports many browsers like Internet explorer, Chrome, Firefox, Opera, Safari etc.
Selenium can be integrated with ANT or Maven kind of framework for source code compilation.
Selenium can be integrated with TestNG testing framework for testing our applications and generating reports.
Selenium can be integrated with Jenkins or Hudson for continuous integration.
Selenium can be integrated with other open source tools for supporting other features.
Selenium can be used for Android, IPhone, Blackberry etc. based application testing.
Selenium supports very less CPU and RAM consumption for script execution.
Selenium comes with different component to provide support to its parent which is Selenium IDE, Selenium Grid and Selenium Remote Control (RC).
Disadvantages:
Selenium needs very much expertise resources. The resource should also be very well versed in framework architecture.
Selenium only supports web based application and does not support windows based application.
It is difficult to test Image based application.
Selenium need outside support for report generation activity like dependence on TestNG or Jenkins.
Selenium does not support built in add-ins support.
Selenium user lacks online support for the problems they face.
Selenium does not provide any built in IDE for script generation and it need other IDE like Eclipse for writing scripts.
Selenium Automation Engineers are bit in scarcity these days.
Selenium script creation time is bit high.
Selenium does not support file upload facility.
Selenium partially supports for Dialog boxes.
From Which selenium version onwards –we have to use gecko driver for firefox?
Selenium 3.0
How to skip a test case in TestNG?
@Test(enabled=false) annotation is used to skip a test case in TestNG
How to find whether an element is a Multidrop down or not?
By using isMultiple()
For example:
Boolean b=driver.findElement(By.id(“year”)).isMultiple();
System.out.println(b);
It retuns true if the element is multi drop down else false
What is the difference between getText() and getAttribute() ?
getText(): It is used to retrieve the text of a Text Element from the web page
For Example:
String Text = driver.findElement(By.id(“Text”)).getText();
getAttribute(): It is used to retrieve the text from a Text Field that is already eneterd into the text field.
For Example:
String Text = driver.findElement(By.id(“username”)).getAttribute();
How to select value in a dropdown?
To handle drop down, an object to be created to the Select class.
Select dropDown= new Select(element);
The value in the dropdown can be selected using 3 ways:
Syntax:
selectByValue()
selectByVisibleText()
selectByIndex()
What is the difference between driver.close() and driver.quit() command?
close(): This method is used to close the current active window of the browser.
quit(): This method is used to close all the associated windows of the browser that are opened.
How to handle Javascript Alerts or web-based pop-ups?
To handle Javascript Alerts, WebDriver provides an Interface called Alert.
First, we need to switch the driver focus to alerts.
Syntax:
Alert alert=driver.switchTo().alerts();
alert.getText() – The getText() method retrieves the text displayed on the alert box.
alert.accept() – The accept() method clicks on the “Ok” button as soon as the pop-up window appears.
alert.dismiss() – The accept() method clicks on the “Cancel” button as soon as the pop-up window appears.
alert.sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
How to capture screenshot in WebDriver?
public String getScreenshot() throws Exception {
try {
driver.get(“https://www.google.co.in/”);
driver.findElement(By.linkText(“Gmail”)).click();
return “Pass”;
}
catch(Exception e) {
DateFormat dateFormat = new SimpleDateFormat(“dd-MM-yyyy HH-mm-ss”);
Date dt = new Date();
File screenshotFile = ((TakesScreenshot) d).getScreenshotAs (OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File(“F:\\Selenium_Scripts_Feb17\\Results\\”+dateFormat.format(dt)+”.png”));
return “Fail”;
}
}
Write a code to login into any site showing uthentication pop-up for username and password?
//Pass Username and Password in URL itself
driver.get(“http://username:password@www.xyz.com”);
How do you send ENTER key?
driver.findElement(By.id(“email”)).sendKeys(Keys.ENTER);
How do you access Firefox profiles in WebDriver?
//create object of ProfilesIni class which holds all the profiles of FF
ProfilesIni pr=new ProfilesIni():
//To load the profile
FirefoxProfile fp=pr.get(“user”);
WebDriver driver=new FirefoxDriver(fp);
driver.get(“http://google.com”);
What are the different types of Waits or Synchrinization commands in WebDriver?
Usually, the time delay between two webdriver elements is 0 milliseconds but the application speed varies based on different factors:
Internet speed
Server response time
System configuration
To avoid the timing errors(Synchronization errors) between the tool (webdriver) and application, we take the help of Synchronization commands.
Implicit Wait: It is used to define wait for all the elements of WebDriver.
Syntax:
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Explicit Wait: It is used to define wait for specific element of WebDriver.
Syntax:
WebDriverWait wait=new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.linkText(“Gmail”)));
Write a syntax to scroll down a page in selenium?
JavascriptExecutor jsx=((JavascriptExecutor) driver);
jsx.executeScript(“window.scrollBy(0,500)”,””);
How to check if text is present on a web page?
String text=”Selenium”;
boolean isTextPresent=(driver.getPageSource()).contains(text);
System.out.println(text+” is present in the web page”);
What are the different exceptions in Selenium web driver?
The different exceptions in Selenium web drivers are
WebDriverException
ElementNotVisibleException
NoAlertPresentException
NoSuchWindowException
NoSuchElementException
TimeoutException
StaleElementReferenceException
How to handle MouseHover?
By using moveToElement() method in Actions class
//Create an object to Actions class
Actions action = new Actions(driver);
action.moveToElement(element);
How to handle Frames?
driver.switchTo().frames(id/name/index/loactor);
How to switch from child frame to parent frame?
To switch back from child frame to parent frame use method parentFrame()
Syntax:
driver.switchTo().parentFrame();
Explain how to switch back from a frame?
To switch back from a frame use method defaultContent()
Syntax:
driver.switchTo().defaultContent();
What is the difference between “/” and “//”
Single Slash “/” – Single slash is used to create XPath with absolute path i.e. it locates the element from the root node.
Example:
/html/body/div[2]/div[4]/table/tbody/tr[4]/td/span
Double Slash “//” – Double slash is used to create XPath with relative path i.e. it locates the element from the current node.
Example:
//input[@name=’email’]
What is the difference between Assert and Verify in Selenium?
There is no difference between Assert and Verify in a positive scenario.
Assert: If the assert condition is true then the program control will execute the next test step but if the condition is false, the execution will stop and further test step will not be executed.
Verify: If the verify condition is true then the program control will execute the next test step but if the condition is false, the execution of the current step will be skipped and further test step will be executed.
What is the super interface of WebDriver?
SearchContext is the super interface of WebDriver
How many ways can we load a web page?
We can load a webpage(url) in two ways:
driver.get(“URL”);
driver.navigatr().to(“URL”);
How can we maximize browser window and delete cookies in Selenium?
To maximize browser window in selenium we use maximize() method.
Syntax:
driver.manage().window().maximize();
To delete cookies we use deleteAllCookies() method.
Syntax:
driver.manage().deleteAllCookies();
Automation Testing Lifecycle?
Requirement Gathering
Analysis
Designing
Development
Testing
Maintenance
What is Selenium?
Selenium is Open source tool.
Selenium supports to automate the web applications.
Selenium is a suite of Software tools. It is a not a single tool. With the help of other third-party tools will build a selenium framework.
It will support various browsers
It will support various Languages
It will support various operating Systems.
List out the Selenium Components?
IDE – Selenium Integrated Development Environment
RC- Selenium Remote Control
WebDriver
Selenium Grid
Difference between Selenium & QTP?
Selenium QTP
Open Source Paid
More Add-Ons we can use Limited add-ons Only
It will support multiple browsers It will support only Firefox, Chrome, IE
Supports different OS It will support only Windows
It will support Mobile Devices QTP Supports Mobile app test automation (iOS & Android) using HP solution called – HP Mobile Center
Can execute tests while the browser is minimized Not Possible here
Can execute tests in parallel. Can only execute in parallel but using Quality Center which is again a paid product.
Selenium Experienced Level Advanced Interview Questions And Answers |
What are all the collections concepts mainly will use in selenium?
List
Set
What is the difference between verification and validation?
Verification: Are we building the application or not – to verify this approach is called as “Verification”.
Validation: Are we building the right application or not – to verify this approach is called as “Validation”.
What are all the Testing types we can able to perform using with Automation Testing tool?
Functional Testing: Functional testing is performed using the functional specification provided by the client and verifies the system against the functional requirements.
Ex: All keyboard keys are working properly or not.
Regression Testing: New functionality changes should not affect the existing functionality.
Reusability of code
Maximum coverage
Recovery scenario
Low-cost maintenance
Minimal manual intervention
Easy Reporting
How to handle Alerts in Selenium?
Will use switchTo() method. Please check the below scenarios.
void dismiss() // To click on the ‘Cancel’ button of the alert.
driver.switchTo().alert().dismiss();
void accept() // To click on the ‘OK’ button of the alert.
driver.switchTo().alert().accept();
String getText() // To capture the alert message.
driver.switchTo().alert().getText();
void sendKeys(String stringToSend) // To send some data to alert box.
driver.switchTo().alert().sendKeys(“Text”);
Explain about Framework using in your project?
You need to clearly explain the following steps:
First, you need to answer why you selected this framework.
How you are maintaining your test suites /cases.
Passing of test data to your test suite/test cases.
Object repository.
Test case execution.
Library folders.
Log files generation.
Test report generation.
Configuration files.
Interviewer cross verifies you by asking versions you are using, we should be ready to answer it.
What is TestNG Data Provider? Write a Syntax for it?
@Test method receives data from this DataProvider. dataProvider name equals to the name of this annotation.
Syntax : @DataProvider(name = “DataProvidename”)
How you will get the title of the page?
driver.getTtile();
How you will get the current URL of the page?
driver.getCurrentUrl();
How to achieve synchronization process in Selenium WebDriver?
Unconditional Synchronization
– Thread.sleep();
Conditional Synchronization
– Implicit Wait
– Explicit Wait
How to handle hidden elements in Selenium WebDriver?
There is no method defined in WebDriver to handle hidden elements and hence we can not handle hidden elements in Selenium.
But through Javascript we can achieve the same.
Syntax:
JavascriptExecutor jsx=((JavascriptExecutor) driver);
jsx.executeScript(“document.getElementsByClassName(element).click();”);
List some scenarios which we cannot automate using Selenium WebDriver?
Bitmap comparison Is not possible using Selenium WebDriver
Automating Captcha is not possible using Selenium WebDriver
We can not read barcode using Selenium WebDriver
We can not automate OTP
How to Upload a file in Selenium WebDriver?
We can Upload a file in Selenium WebDriver directly by passing the Path of the file as an argument to the sendKeys() if the element contains “type=file” in the source code.
Syntax:
driver.findElement(By.xapth(“//div[@type=’file’]”)).sendKeys(“C://Downloads/Resume.html”);
If the element does not contains “type=file” in the source code then uploading a file in Selenium WebDriver can be handled by using Robot class or AutoIT.
How to set test case priority in TestNG?
We can set test case priority in TestNG by using priority attribute to the @Test annotations.
Example:
@Test(priority=2)
public void m1(){
System.out.println(“This is m1 method”);
}
@Test(priority=1)
public void m2(){
System.out.println(“This is m2 method”);
}
Output:
This is m2 method
This is m1 method
What is the default port used by Hub in Selenium Grid?
The default port used by the hub is 4444
How do u get the width of the textbox?
driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getWidth();
driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getHeight();
Is WebElement an interface or a class ?
WebElement is an Interface.
What is the default port used by Node in Selenium Grid?
The default port used by the Node is 5555
What are all the Wait conditions in Selenium? Difference between implicitly Wait, Explicitly Wait and Fluent Wait?
Implicit Wait:
Selenium Web Driver has borrowed the idea of implicit waits from Watir.
The implicit wait will tell to the web driver to wait for certain amount of time before it throws a “No Such Element Exception”.
The default setting is 0. Once we set the time, web driver will wait for that time before throwing an exception.
It is for Page Level.
Syntax:
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
Explicit Wait:
This wait method for Element level.
The explicit wait is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or the maximum time exceeded before throwing an “ElementNotVisibleException” exception.
The explicit wait is an intelligent kind of wait, but it can be applied only for specified elements.
Explicit wait gives better options than that of an implicit wait as it will wait for dynamically loaded Ajax elements.
Syntax:
WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
Fluent Wait uses two parameters – timeout value and polling frequency.
First of all, it sets the following values.
1- The maximum amount of time to wait for a condition, and
2- The frequency to check the success or failure of a specified condition.
Also, if you want to configure the wait to ignore exceptions such as <NoSuchElementException>
Syntax :
Wait wait = new FluentWait(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id(“foo”));
}
});
Step By Step Analysis Of The Above Sample Code.
Step-1: Fluent Wait starts with capturing the start time to determine delay.
Step-2: Fluent Wait then checks the condition defined in the until() method.
Step-3: If the condition fails, Fluent Wait makes the application to wait as per the value set by the <pollingEvery(5, SECONDS)> method call. Here in this example, it’s 5 seconds.
Step-4: After the wait defined in Step 3 expires, start time is checked against the current time. If the difference of the wait start time (set in step-1) and the current time is less than the time set in <withTimeout(30, SECONDS)> method, then Step-2 will need to repeat.
The above steps will recur until either the timeout expires or the condition becomes true.
How to Handle 2 Frames?
to switchto a frame:
driver.switchTo.frame(“Frame_ID”);
to switch to the default again.(parent)
driver.switchTo().defaultContent();
Explain About Maven concept?
Maven simplifies the code handling and process of building the project. Most of the projects follow maven structure.
Download all dependencies provided the dependencies are available in maven central repository. If any of the dependency is not available in maven central repository then you have to add repository path in pom.xml explicitly.
There are many other build tools available in like ant. But it is better to use maven while dealing with different versions and different dependencies. Maven even can manage the dependencies of dependencies. Other tools may not provide such flexibility like maven
Why Jenkins and Selenium?
Running Selenium tests in Jenkins allows you to run your tests every time your software changes and deploy the software to a new environment when the tests pass.
Jenkins can schedule your tests to run at specific time.
You can save the execution history and Test Reports.
Jenkins supports Maven for building and testing a project in continuous integration.
How to capture the color of Web Element or text color in WebDriver?
You can get the element color(Background color of element) by:
element.getCssValue(“background-color”);
You can get the element text/caption color by:
element.getCssValue(“color”);
How to handle 2 windows or explain window handling.
driver.getWindowHandle(); – Single Window
driver.getWindowHandles(); – Multiple windows
Difference between ANT and MAVEN?
Ant Maven
Ant doesn’t has formal conventions, so we need to provide information of the project structure in build.xml file. Maven has a convention to place source code, compiled code etc. So we don’t need to provide information about the project structure in pom.xml file.
Ant is procedural. You need to provide information about what to do and when to do through code. You need to provide order. Maven is declarative, everything you define in the pom.xml file.
There is no life cycle in Ant. There is life cycle in Maven.
It is a tool box. It is a framework.
It is mainly a build tool. It is mainly a project management tool.
The ant scripts are not reusable. The maven plugins are reusable.
It is less preferred than Maven. It is more preferred than Ant.
What is latest version of Selenium WebDriver?
3.11
How to Upload the file in selenium?
Using with SendKeys
RobotClass
AutoIT
List out some TestNG Annotations.?
@BeforeSuite – Before Suite will always execute prior to all annotations or tests in the suite.
@BeforeTest – Before Test will always execute prior to Before Class, ,Before Method and Test Method
@BeforeClass – Before Class will always execute prior to Before Method and Test Method
@BeforeMethod – Before Method will execute before every test method
@AfterMethod – After Method will execute after every test method
@AfterClass – After Class will always execute later to After Method and Test method
@AfterTest – After Test will always execute later to After Method, After Class
@AfterSuite – After suite will always execute at last when all the annotations or test in the suite have run
@Test – Mandatory annotation.
How you will share your output to managers?
TestNG – Emailable Report or XSLT Report.
How to merge all your team members’ code and how you will run?
Git Repository or SVN
How to read and Write the Data from Excel Sheet?
Read Excel Data : FileInputStream.
Write Excel data : FileOutStream
What is the difference between xpath and css selector?
CSS selectors perform far better than Xpath. Majorly in IE Browser.
Xpath : powerful selection of the DOM
CSS : looks simpler. consistent support across browsers
XPATH: no native support for xpath in IE (WebDriver uses a 3rd party library)
CSS: Tests may need to be updated with UI changes
Xpath engines are different in each browser, hence make them inconsistent
IE does not have a native xpath engine, therefore selenium injects its own xpath engine for compatibility of its API. Hence we lose the advantage of using native browser features that WebDriver inherently promotes.
Xpath tend to become complex and hence make hard to read
Explain Testng.xml structure. ( Suite-> Test> Classes>Class)?
Example:
<?xml version=”1.0″ encoding=”UTF-8″?>
<suite name=”example suite 1″ verbose=”1″ >
<test name=”Regression suite 1″ >
<classes>
<class name=”com.first.example.demoOne”/>
<class name=”com.first.example.demoTwo”/>
<class name=”com.second.example.demoThree”/>
</classes>
</test>
</suite>
We need to specify the class names along with packages in between the classes’ tags.
What are all the challenges you have faced while doing the Automation.?
Dealing with pop-up windows:
Selenium can sometimes fail to record common popups in web apps. To handle any kind of alert popup, you can apply a getAlert function. Before actually running the script, you must import a package that can generate a WebDriver script for handling alerts. The efficient interface brings with it the following commands: void dismiss(), void accept (), getText(), void sendKeys(String stringToSend). The first two basically click on the “cancel” and “OK” buttons respectively on a popup window.
No event trigger from value changes:
Because Selenium does not initiate events with a change in values, one must do it oneself using fireEvent: selenium.FireEvent(cmbCategory, “onchange”);
Timeout resulting from synchronization problems:
One should ideally use selenium.IsElementPresent(locator) to verify that the object is in a loop with Thread.Sleep
Testing Flash apps:
To automate flash apps with Selenium, one can use Flex Monkium. The application source code must be compiled with the swc files generated by Flex Monkium. Then the app and the Selenium IDE are connected, and the tests can be recorded with IDE.
Unexpected error launching Internet Explorer. Browser zoom level should be set to 100% by default for the IE browser to overcome this error.
Protected Mode must be set to the same value error occurs when trying to run Selenium WebDriver on a fresh Windows machine. This issue can be fixed by using capabilities as below when launching IE.
What are Exception and Error? Specify the Difference.?
Exception: Exception occurs in the programmer’s code .which can be handled and resolvable.
Ex: arithmetic exception
DivideByZeroException
NullPointerException
ClassNotFoundException
Error: Errors are not resolvable by the programmer. Error occurs due to lack of system resources.
Ex: Stack overflow
hardware error
JVM error
Why Exception Handling important in Selenium?
To continue the flow of execution.
Most Common Exceptions Which We Notice In Selenium WebDriver?
NoSuchElementException: An element could not be located on the page using the given search parameters.
NoSuchFrameException: A request to switch to a frame could not be satisfied because the frame could not be found.
StaleElementReferenceException: An element command failed because the referenced element is no longer attached to the DOM.
Firefox Not Connected Exception: Firefox browser upgraded to new version.
ElementIsNotSelectable Exception: An attempt was made to select an element that cannot be selected.
unknown command Exception: The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource.
ElementNotVisible Exception: An element command could not be completed because the element is not visible on the page.
InvalidElementState Exception: An element command could not be completed because the element is in an invalid state (e.g. attempting to click a disabled element).
UnknownError Exception: An unknown server-side error occurred while processing the command.
javascript error Exception: An error occurred while executing JavaScript code.
XPathLookupError Exception: An error occurred while searching for an element by XPath.
Timeout Exception: An operation did not complete before its timeout expired.
NoSuchWindow Exception: A request to switch to a different window could not be satisfied because the window could not be found.
InvalidCookieDomain Exception: An illegal attempt was made to set a cookie under a different domain than the current page.
UnableToSetCookie Exception: A request to set a cookie’s value could not be satisfied.
UnexpectedAlertOpen Exception: A modal dialog was open, blocking this operation
NoAlertOpenError Exception: An attempt was made to operate on a modal dialog when one was not open.
ScriptTimeout Exception: A script did not complete before its timeout expired.
InvalidElementCoordinates Exception: The coordinates provided to an interactions operation are invalid.
InvalidSelector Exception: Argument was an invalid selector (e.g. XPath/CSS).
Explain the difference between Absolute XPath and relative XPath?
Types of X-path
There are two types of XPath:
1) Absolute XPath.
2) Relative XPath.
Absolute XPath:
It is the direct way to find the element.
It will start with the single forward slash(/) – which means you can select the element from the root node.
Ex : html/body/div[1]/section/div[1]/div/div/div/div[1]/div/div/div/div/div[3]/div[1]/div/h4[1]/b
Disadvantage:
If there are any changes made in the path of the element then that XPath gets failed.
Relative XPath:
It will starts from the middle of the HTML. It starts with the double forward slash (//).
It which means it can search the element anywhere on the webpage.
Ex : //*[@class=’featured-box’]//*[text()=’Testing’]
How to Priority your tests in TestNG?
Ex: @Test (priority=1)
16. How to handle Ajax calls?
AJAX allows the Web page to retrieve small amounts of data from the server without reloading the entire page.
To test Ajax application, different wait methods should be applied
ThreadSleep
Implicit Wait
Explicit Wait
WebdriverWait
Fluent Wait
How to handle Ajax calls?
AJAX allows the Web page to retrieve small amounts of data from the server without reloading the entire page.
To test Ajax application, different wait methods should be applied
ThreadSleep
Implicit Wait
Explicit Wait
WebdriverWait
Fluent Wait
How do you execute your framework from command prompt?
Home-directory > java org,testng.TestNG testng.xml testng2.xml testng2.xml and hit enter
Difference between WebDriver Listener and TestNG listener.
TestNG and Web driver Listener have different interfaces to implement and call them.
WebDriver Event Listener is to listen the events triggered by web driver like beforeClickOn, afterClickOn, beforeFindBy, afterFindBy, etc. and take actions. It is mainly used to write log file for selenium test execution.
TestNG listener mainly used to generate the report for the test. Also, you can capture screenshot when there is test failure. TestNG events are like onTestFailure, onTestSkipped, onTestSuccess, etc.
How you will find the row count and column Count in dynamic web table?
Rows: List<WebElement> rows=htmltable.findElements(By.tagName(“tr”));
Col: List<WebElement> columns=rows.get(rnum).findElements(By.tagName(“th”));
WebDriver is interface or class?
WebDriver is interface
Firefox Browser is interface or class?
FirefoxDriver is Class
Syntax to declare chrome browser and Gecko driver and Firefox Browser and IE browser?
Gecko Driver :
System.setProperty(“webdriver.gecko.marionette”, “Path Of Exe”);
WebDriver driver = new FirefoxDriver();
Chrome Driver:
System.setProperty(“webdriver.chrome.driver”,”Path of Exe”);
//create chrome instance
WebDriver driver = new ChromeDriver();
IE Driver :
System.setProperty(“webdriver.ie.driver”,”Path of Exe “);
//create IE instance
WebDriver driver = new InternetExplorerDriver();
Write a Syntax for Drag and Drop?
Actions act = new Actions(driver);
WebElement From = driver.findElement(By.id(“draggable”));
WebElement To = driver.findElement(By.id(“droppable”));
act.dragAndDrop(From, To).build().perform();
Write Syntax for Mouse Hover Element?
Actions act = new Actions(driver);
action.moveToElement(element).build().perform()
Write Syntax for Double Click?
Actions act = new Actions(driver);
action.doubleClick(element).build().perform();
Write Syntax for Right Click?
Actions act = new Actions(driver);
action.contextClick(element).build().perform();
Difference between Apache POI and Jxl jar files?
JExcel Apache POI
It doesn’t support Excel 2007 and Xlsx format. It supports only Excel 2003 and .Xls format It supports both
JXL doesn’t support Conditional formatting It supports
JXL API was last updated in 2009 Apache POI is actively maintained
It doesn’t support rich text formatting Apache POI supports it
It has very less documents and examples as compare to Apache POI It has extensive set of documents and examples
What are all the element locators in Selenium?
Id
Name
CSSSelector
Xpath
Tagname
ClassName
LinkText
Partial LinkText
How to Handle Dropdown Values in selenium. Write a syntax and types to handle the dropdpwn Box?
Using with Select Class
Syntax:
Select sel = new Select(driver.findElement(By.id(“test”));
Sel.SelectByVisibleText(“value”);
Sel.SelectByValue(“2”);
Sel.SelectByIndex(4);
When will you get element not clickable exception in Selenium?
The reason for the element is not clickable at point(x,y) exception.
Some of my observation was
It mostly happens in Chrome so if you are mostly working with Firefox or IE then you will not be getting this exception.
Chrome does not calculate the exact location of element
Chrome always click in the middle of Element.
Sometimes you will get this exception due to Sync issue also.
How to solve Not connected Exception – unable to connect to host in selenium webdriver?
Scripts that worked earlier may be till yesterday are NOW not working because of Firefox browser upgraded to new version.
Most of them have faced the similar problem when the browser has updated to version. This is the first issue user notices when there is an update in the Firefox browser and may not support selenium with the older version of jars.
If you already have the latest version of selenium, then you have to degrade your browser until there is an update from selenium.
Problem :
Webdriver will just initiate the browser, prompting for a search or address and that ends there with an exception:
org.openqa.selenium.firefox.NotConnectedException:
What is Selenium?
Selenium is a Suite (group) of tools i.e., Selenium IDE, Selenium WebDriver and Selenium Grid to automate web browsers across many platforms.
What is Selenium IDE, WebDriver, and Grid?
Selenium IDE: It is a Firefox plugin which is used to Record and Play the Test Scripts.
Selenium WebDriver: It is a tool which provides an API (that can be understood easily) to automate web browsers with the help of programming languages like Java, Csharp, Python, PHP, Perl, Ruby, and JavaScript.
Selenium Grid: It transparently distributes tests into Remote machines. That is, running multiple tests at the same time against different machines running different browsers and operating systems.
What are the locators available in WebDriver?
Locators: Locators are used to identifying or locate an element (text box, radio buttons, links, check boxes, drop downs, images, text etc. ) in the web page.
Webdriver supports 8 locators i.e., Id, Name, Class Name, Link Text, Partial Link Text, XPath, CSS and Tag Name.
Note: Id is the fastest locator among this 8 locators.
How to launch Firefox, Chrome, IE browser using WebDriver?
The following syntax can be used to launch Browser:
WebDriver driver = new FirefoxDriver();
WebDriver driver = new ChromeDriver();
WebDriver driver = new InternetExplorerDriver();
How to set System Property in WebDriver?
We can set the system property by using setProperty() method, which is a static method defined in System class for which we need to pass 2 parameters i.e., driver name and path of the executable file of the driver.
For Example Setting system property to launch chrome browser
public class ChromeBrowser {
WebDriver driver;
public static void main(String[] args) {
System.setProperty(“webdriver.chrome.driver”, “E://chromedriver.exe”);
driver = new ChromeDriver();
driver.get(“http://www.google.com”);
}
}
How to find font color of Text element?
By using getCssvalue()
For example:
driver.findElement(By.id(“text”)).getCssValue(“color”);
How to find size of the Image?
By using getSize()
How to find Dynamic Web Elements?
We can Dynamic web elements with the help of XPath or CSS.
For Example:
By using XPath:
driver.findElement(By.xpath(“//div[contains(@id,’yui_’)]”));
By using CSS:
driver.findElement(By.cssSelector(“div[id*=’yui_’)]”));
How to skip a test case in JUnit?
By using @Ignore annotation
@Ignore
@Test
public void testDemo(){
System.out.println(“This is testDemo Method”);
}
@Test
public void testPractice(){
System.out.println(“This is testPractice Method”);
}
Output:
This is testPractice Method
Note: Execution in JUnit is carried out in Alphabetical Order
Which is more preferable xpath or CSS?
CSS Selector
How to find out all the links in webpage?
List<WebElement> allLinks = driver.findElements(By.tagName(“a”));
How we will configure the Parallel browser testing in testng.xml?
<suite name=”Parallel test suite” parallel=”tests”>
Explain about TestNG – its listeners?
ITestListener has following methods
OnStart – OnStart method is called when any Test starts.
onTestSuccess– onTestSuccess method is called on the success of any Test.
on test failure– on test failure method is called on the failure of any Test.
onTestSkipped – onTestSkipped method is called on skipped of any Test.
onTestFailedButWithinSuccessPercentage – method is called each time Test fails but is within success percentage.
onFinish – onFinish method is called after all Tests are executed
Write a Syntax to take the screenshot?
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//The below method will save the screen shot in d drive with name “screenshot.png”
FileUtils.copyFile(scrFile, new File(“D:\\screenshot.png”));
How to find out all the frames in a webpage?
List<WebElement> ele = driver.findElements(By.tagName(“frame”));
System.out.println(“Number of frames in a page :” + ele.size());
How to handle cookies?
In Selenium Webdriver interact with cookies with below built-in methods
driver.manage().getCookies(); // Return The List of all Cookies
driver.manage().getCookieNamed(arg0); //Return specific cookie according to name
driver.manage().addCookie(arg0); //Create and add the cookie
driver.manage().deleteCookie(arg0); // Delete specific cookie
driver.manage().deleteCookieNamed(arg0); // Delete specific cookie according Name
driver.manage().deleteAllCookies(); // Delete all cookies
What is Selenium Grid?
Selenium Grid is a tool used together with Selenium RC to run parallel tests across different machines and different browsers all at the same time. Parallel execution means running multiple tests at once.
Features:
Enables simultaneous running of tests in multiple browsers and environments.
Saves time enormously.
Utilizes the hub-and-nodes concept. The hub acts as a central source of Selenium commands to each node connected to it.
Difference between find elements and find element?
FINDELEMENT() METHOD:
FindElement method is used to access a single web element on a page. It returns the first matching element. It throws a NoSuchElementException exception when it fails to find If the element.
Syntax:
driver.findElement(By.xpath(“Value of Xpath”));
FINDELEMENTS() METHOD:
FindElements method returns the list of all matching elements. The findElement method throws a NoSuchElementException exception when the element is not available on the page. Whereas, the findElements method returns an empty list when the element is not available or doesn’t exist on the page. It doesn’t throw NoSuchElementException.
Syntax:
List link = driver.findElements(By.xpath(“Value of Xpath”));
Explain about softAssert and HardAssert?
Asserts are used to perform validations in the test scripts.
There are two types of Assert:
Hard Assert
Soft Assert
When an assert fails the test script stops execution unless handled in some form. We call general assert as Hard Assert.
Hard Assert – Hard Assert throws an AssertExceptionimmediately when an assert statement fails and test suite continues with next @Test.
The disadvantage of Hard Assert – It marks method as fail if assert condition gets failed and the remaining statements inside the method will be aborted.
To overcome this we need to use Soft Assert. Let’s see what is Soft Assert.
Soft Assert – Soft Assert collects errors during @Test. Soft Assert does not throw an exception when an assert fails and would continue with the next step after the assert statement.
If there is any exception and you want to throw it then you need to use assertAll() method as a last statement in the @Test and test suite again continue with next @Test as it is.
We need to create an object to use Soft Assert which is not needed in Hard Assert.
How to Start Jenkins in command Promt?
D:\>Java –jar Jenkins.war
What is the latest version of Jenkins?
Jenkins 2.114
What is Page Object Model?
Page Object Model Framework has now a days become very popular test automation framework in the industry and many companies are using it because of its easy test maintenance and reduces the duplication of code.
The main advantage of Page Object Model is that if the UI changes for any page, it don’t require us to change any tests, we just need to change only the code within the page objects (Only at one place).
The Page Object model provides the following advantages.
There is clean separation between test code and page specific code such as locators (or their use if you’re using a UI map) and layout.
There is single repository for the services or operations offered by the page rather than having these services scattered throughout the tests.
What is the default port for selenium Grid?
The default port used by the hub is 4444
Selenium advantages and disadvantages?
Advantages:
Selenium is pure open source, freeware and portable tool.
Selenium supports variety of languages that include Java, Perl, Python, C#, Ruby, Groovy, Java Script, and VB Script. etc.
Selenium supports many operating systems like Windows, Macintosh, Linux, Unix etc.
Selenium supports many browsers like Internet explorer, Chrome, Firefox, Opera, Safari etc.
Selenium can be integrated with ANT or Maven kind of framework for source code compilation.
Selenium can be integrated with TestNG testing framework for testing our applications and generating reports.
Selenium can be integrated with Jenkins or Hudson for continuous integration.
Selenium can be integrated with other open source tools for supporting other features.
Selenium can be used for Android, IPhone, Blackberry etc. based application testing.
Selenium supports very less CPU and RAM consumption for script execution.
Selenium comes with different component to provide support to its parent which is Selenium IDE, Selenium Grid and Selenium Remote Control (RC).
Disadvantages:
Selenium needs very much expertise resources. The resource should also be very well versed in framework architecture.
Selenium only supports web based application and does not support windows based application.
It is difficult to test Image based application.
Selenium need outside support for report generation activity like dependence on TestNG or Jenkins.
Selenium does not support built in add-ins support.
Selenium user lacks online support for the problems they face.
Selenium does not provide any built in IDE for script generation and it need other IDE like Eclipse for writing scripts.
Selenium Automation Engineers are bit in scarcity these days.
Selenium script creation time is bit high.
Selenium does not support file upload facility.
Selenium partially supports for Dialog boxes.
From Which selenium version onwards –we have to use gecko driver for firefox?
Selenium 3.0
How to skip a test case in TestNG?
@Test(enabled=false) annotation is used to skip a test case in TestNG
How to find whether an element is a Multidrop down or not?
By using isMultiple()
For example:
Boolean b=driver.findElement(By.id(“year”)).isMultiple();
System.out.println(b);
It retuns true if the element is multi drop down else false
What is the difference between getText() and getAttribute() ?
getText(): It is used to retrieve the text of a Text Element from the web page
For Example:
String Text = driver.findElement(By.id(“Text”)).getText();
getAttribute(): It is used to retrieve the text from a Text Field that is already eneterd into the text field.
For Example:
String Text = driver.findElement(By.id(“username”)).getAttribute();
How to select value in a dropdown?
To handle drop down, an object to be created to the Select class.
Select dropDown= new Select(element);
The value in the dropdown can be selected using 3 ways:
Syntax:
selectByValue()
selectByVisibleText()
selectByIndex()
What is the difference between driver.close() and driver.quit() command?
close(): This method is used to close the current active window of the browser.
quit(): This method is used to close all the associated windows of the browser that are opened.
How to handle Javascript Alerts or web-based pop-ups?
To handle Javascript Alerts, WebDriver provides an Interface called Alert.
First, we need to switch the driver focus to alerts.
Syntax:
Alert alert=driver.switchTo().alerts();
alert.getText() – The getText() method retrieves the text displayed on the alert box.
alert.accept() – The accept() method clicks on the “Ok” button as soon as the pop-up window appears.
alert.dismiss() – The accept() method clicks on the “Cancel” button as soon as the pop-up window appears.
alert.sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
How to capture screenshot in WebDriver?
public String getScreenshot() throws Exception {
try {
driver.get(“https://www.google.co.in/”);
driver.findElement(By.linkText(“Gmail”)).click();
return “Pass”;
}
catch(Exception e) {
DateFormat dateFormat = new SimpleDateFormat(“dd-MM-yyyy HH-mm-ss”);
Date dt = new Date();
File screenshotFile = ((TakesScreenshot) d).getScreenshotAs (OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File(“F:\\Selenium_Scripts_Feb17\\Results\\”+dateFormat.format(dt)+”.png”));
return “Fail”;
}
}
Write a code to login into any site showing uthentication pop-up for username and password?
//Pass Username and Password in URL itself
driver.get(“http://username:password@www.xyz.com”);
How do you send ENTER key?
driver.findElement(By.id(“email”)).sendKeys(Keys.ENTER);
How do you access Firefox profiles in WebDriver?
//create object of ProfilesIni class which holds all the profiles of FF
ProfilesIni pr=new ProfilesIni():
//To load the profile
FirefoxProfile fp=pr.get(“user”);
WebDriver driver=new FirefoxDriver(fp);
driver.get(“http://google.com”);
What are the different types of Waits or Synchrinization commands in WebDriver?
Usually, the time delay between two webdriver elements is 0 milliseconds but the application speed varies based on different factors:
Internet speed
Server response time
System configuration
To avoid the timing errors(Synchronization errors) between the tool (webdriver) and application, we take the help of Synchronization commands.
Implicit Wait: It is used to define wait for all the elements of WebDriver.
Syntax:
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Explicit Wait: It is used to define wait for specific element of WebDriver.
Syntax:
WebDriverWait wait=new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.linkText(“Gmail”)));
Write a syntax to scroll down a page in selenium?
JavascriptExecutor jsx=((JavascriptExecutor) driver);
jsx.executeScript(“window.scrollBy(0,500)”,””);
How to check if text is present on a web page?
String text=”Selenium”;
boolean isTextPresent=(driver.getPageSource()).contains(text);
System.out.println(text+” is present in the web page”);
What are the different exceptions in Selenium web driver?
The different exceptions in Selenium web drivers are
WebDriverException
ElementNotVisibleException
NoAlertPresentException
NoSuchWindowException
NoSuchElementException
TimeoutException
StaleElementReferenceException
How to handle MouseHover?
By using moveToElement() method in Actions class
//Create an object to Actions class
Actions action = new Actions(driver);
action.moveToElement(element);
How to handle Frames?
driver.switchTo().frames(id/name/index/loactor);
How to switch from child frame to parent frame?
To switch back from child frame to parent frame use method parentFrame()
Syntax:
driver.switchTo().parentFrame();
Explain how to switch back from a frame?
To switch back from a frame use method defaultContent()
Syntax:
driver.switchTo().defaultContent();
What is the difference between “/” and “//”
Single Slash “/” – Single slash is used to create XPath with absolute path i.e. it locates the element from the root node.
Example:
/html/body/div[2]/div[4]/table/tbody/tr[4]/td/span
Double Slash “//” – Double slash is used to create XPath with relative path i.e. it locates the element from the current node.
Example:
//input[@name=’email’]
What is the difference between Assert and Verify in Selenium?
There is no difference between Assert and Verify in a positive scenario.
Assert: If the assert condition is true then the program control will execute the next test step but if the condition is false, the execution will stop and further test step will not be executed.
Verify: If the verify condition is true then the program control will execute the next test step but if the condition is false, the execution of the current step will be skipped and further test step will be executed.
What is the super interface of WebDriver?
SearchContext is the super interface of WebDriver
How many ways can we load a web page?
We can load a webpage(url) in two ways:
driver.get(“URL”);
driver.navigatr().to(“URL”);
How can we maximize browser window and delete cookies in Selenium?
To maximize browser window in selenium we use maximize() method.
Syntax:
driver.manage().window().maximize();
To delete cookies we use deleteAllCookies() method.
Syntax:
driver.manage().deleteAllCookies();
Post a Comment