We Offer 100% Job Guarantee Courses (Any Degree / Diploma Candidates / Year GAP / Non-IT / Any Passed Outs). Placement Records
Hire Talent (HR):+91-9707 240 250

Interview Questions

Selenium Interview Questions and Answers

Selenium Interview Questions and Answers

Selenium Interview Questions and Answers

Selenium Interview Questions and Answers for beginners and experts. List of frequently asked Selenium Interview Questions with answers by Besant Technologies. We hope these Selenium interview questions and answers are useful and will help you to get the best job in the networking industry. This Selenium interview questions and answers are prepared by Selenium Professionals based on MNC Companies expectation. Stay tuned we will update New Selenium Interview questions with Answers Frequently. If you want to learn Practical Selenium Training then please go through this Selenium Training in Chennai and Selenium Training in Bangalore

Best Selenium Interview Questions and Answers

Besant Technologies supports the students by providing Selenium interview questions and answers for the job placements and job purposes. Selenium is the leading important course in the present situation because more job openings and the high salary pay for this Selenium and more related jobs. We provide the Selenium online training also for all students around the world through the Gangboard medium. These are top Selenium interview questions and answers, prepared by our institute experienced trainers.

Selenium interview questions and answers for the job placements

Here is the list of most frequently asked Selenium Interview Questions and Answers in technical interviews. These questions and answers are suitable for both freshers and experienced professionals at any level. The questions are for intermediate to somewhat advanced Selenium professionals, but even if you are just a beginner or fresher you should be able to understand the answers and explanations here we give.

Q1. 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”.

Q2. 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.

Q3. Automation Testing Lifecycle? Requirement Gathering
Analysis
Designing
Development
Testing
Maintenance

Q4. 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.

Q5. List out the Selenium Components?

IDE – Selenium Integrated Development Environment
RC- Selenium Remote Control
WebDriver
Selenium Grid

Q6. 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.

Q7. What are all the collections concepts mainly will use in selenium?

List
Set

Q8. Advantages of Automation Framework?

Reusability of code
Maximum coverage
Recovery scenario
Low-cost maintenance
Minimal manual intervention
Easy Reporting

Q9. 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”);

Q10. 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.

Q11.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”)

Q12. 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

Q13. Why Exception Handling important in Selenium?

To continue the flow of execution.

Q14. 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).

Q15. 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)

Q16. 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

Q17. 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

Q18. How do you execute your framework from command prompt?

Home-directory > java org,testng.TestNG testng.xml testng2.xml testng2.xml and hit enter

Q19.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.

Q20. 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”));

Q21. How you will get the title of the page?

driver.getTtile();

Q22. How you will get the current URL of the page?

driver.getCurrentUrl();

Q23.How to achieve synchronization process in Selenium WebDriver?

Unconditional Synchronization
– Thread.sleep();
Conditional Synchronization
– Implicit Wait
– Explicit Wait

Q24. 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.

Q25. How to Handle 2 Frames?

to switchto a frame:
driver.switchTo.frame(“Frame_ID”);
to switch to the default again.(parent)
driver.switchTo().defaultContent();

Q26. 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

Q27. 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.

Q28. 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”);

Q29. How to handle 2 windows or explain window handling?

driver.getWindowHandle();  – Single Window
driver.getWindowHandles();  – Multiple windows

Q30. 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.

Q31. What is latest version of Selenium WebDriver?

3.11

Q32. How to Upload the file in selenium?

Using with SendKeys
RobotClass
AutoIT

Q33. 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.

Q34. How you will share your output to managers?

TestNG – Emailable Report or XSLT Report.

Q35. How to merge all your team members’ code and how you will run?

Git Repository or SVN

Q36. How to read and Write the Data from Excel Sheet?

Read Excel Data : FileInputStream.
Write Excel data : FileOutStream

Q37. 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

Q38. 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.

Q39. 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.

Q40. WebDriver is interface or class?

WebDriver is interface

Q41. Firefox Browser is interface or class?

FirefoxDriver is Class

Q42. 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();

Q43. 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();

Q44. Write Syntax for Mouse Hover Element?

Actions act = new Actions(driver);
action.moveToElement(element).build().perform()

Q45. Write Syntax for Double Click?

Actions act = new Actions(driver);
action.doubleClick(element).build().perform();

Q46. Write Syntax for Right Click?

Actions act = new Actions(driver);
action.contextClick(element).build().perform();

Q47. 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

Q48. What are all the element locators in Selenium?

Id
Name
CSSSelector
Xpath
Tagname
ClassName
LinkText
Partial LinkText

Q49. Which is more preferable xpath or CSS?

CSS Selector

Q50. How to find out all the links in webpage?

List<WebElement> allLinks = driver.findElements(By.tagName(“a”));

Q51. How we will configure the Parallel browser testing in testng.xml?

<suite name=”Parallel test suite” parallel=”tests”>

Q52. 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

Q53. 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.pn” open=”no” style=”default” icon=”plus” anchor=”” class=””]g”
FileUtils.copyFile(scrFile, new File(“D:\\screenshot.png”));

Q54. 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());

Q55. 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

Q56. 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.

Q57. 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”));

Q58. 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.

Q59. How to Start Jenkins in command Promt?

D:\>Java –jar Jenkins.war

Q60. What is the latest version of Jenkins?

Jenkins 2.114

Q61. 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.

Q62. What is the default port for selenium Grid?

The default port used by the hub is 4444

Q63. 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
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.

Q64. From Which selenium version onwards –we have to use gecko driver for firefox?

Selenium 3.0

Q65. 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);

Q66. 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.

Q67. 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:

Q68. 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.

Q69. 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.

Q70. 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.

Q71. 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();

Q72. 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”);
}
}

Q73. How to find font color of Text element?

By using getCssvalue()
For example:
driver.findElement(By.id(“text”)).getCssValue(“color”);

Q74. How to find size of the Image?

By using getSize()

Q75. 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_’)]”));

Q76. 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

Q77. How to skip a test case in TestNG?

Test(enabled=false) annotation is used to skip a test case in TestNG

Q78. 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

Q79. 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();

Q80. 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()

Q81. 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.

Q82. 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.

Q83. 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”;
}
}

Q84. 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”);

Q85. How do you send ENTER key?

driver.findElement(By.id(“email”)).sendKeys(Keys.ENTER);

Q86. 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”);

Q87. 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”)));

Q88. Write a syntax to scroll down a page in selenium?

JavascriptExecutor jsx=((JavascriptExecutor) driver);
jsx.executeScript(“window.scrollBy(0,500)”,””);

Q89. 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”);

Q90. What are the different exceptions in Selenium web driver?

The different exceptions in Selenium web drivers are
WebDriverException
ElementNotVisibleException
NoAlertPresentException
NoSuchWindowException
NoSuchElementException
TimeoutException
StaleElementReferenceException

Q91. 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);

Q92. How to handle Frames?

driver.switchTo().frames(id/name/index/loactor);

Q93. 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();

Q94. Explain how to switch back from a frame?

To switch back from a frame use method defaultContent()
Syntax:
driver.switchTo().defaultContent();

Q95. 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’]

Q96. 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.

Q97. What is the super interface of WebDriver?

SearchContext  is the super interface of WebDriver

Q98. How many ways can we load a web page?

We can load a webpage(url) in two ways:
get(“URL”);
navigatr().to(“URL”);

Q99. 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();

Q100. 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();”);

Q101. 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

Q102. 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.

Q103. 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

Q104. What is the default port used by Hub in Selenium Grid?

The default port used by the hub is 4444

Q105. 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();

Q106. Is WebElement an interface or a class?

WebElement is an Interface.

Q107. What is the default port used by Node in Selenium Grid?

The default port used by the Node is 5555

Q108.What is a Driver?

Driver refers to the Web browser. Selenium can handle web-based testing using any browser hence termed as Selenium WebDriver. A browser can have only one driver instance.

Q109.XPath types and its usage related to tables?

In the web browser, Each of the elements are identified using HTML tags. Inorder to traverse through this HTML tag XPath is mainly used.
Absolute XPath – where we traverse from the root tag to our element needed
Relative XPath – exactly we go to the specified element.
Relative path should be preferred as – no need to update the elements of any changes has occurred in the future. If absolute XPath is used if changes in the elements occurred each & every time the element should be updated.

Q110.Upload and download using AutoIt?

AutoIt uses keyboard event to navigate and download the file in the specified location
What are the different Framework model preferred?
Specflow widely preferred model based on BDD framework which contain Feature file and the related step definition file.

Q111.How to handle IE popup window?

While working with IE, sometimes IE browser popups a window with a message “Do you want to Stay in this Page Or Leave this page?”. This can’t be handled through Selenium.
Solution : by default, Leave this page button will be active just press Enter using keyboard event to continue…

Q112.What is framework on your understanding?

Framework is the model that show how you’re project works in backend.
Framework makes code clean and reasuable.
Framework can be independent based on the testers creativity.
Framework makes code easily understandable and organised.

Q113.How testdata are used in selenium?

It can be created as a constant on either of external files such as JSON,XML, Excel files.

Q114.How the scripts know whether the file is downloaded or not?

In Files, a concept called FileWatcher is available which keeps on watches whether the file is download in the particular location or not.

Q115.Why thread.sleep is not preferred?

Thread sleep makes the browser to be idle for sometime without performing any tasks. This waste the time is not preferred. Because Sometimes when waiting for longer time the browser can lose its scope and become inactive Hence WebDriver waits are preferred instead.

Q116.What is MSTest & how it is different from nunit?

MSTest is supported in C# language which is available by default in the visual Studio used a unit testing tool. Where nunit is also a testing tool which should be downloaded and configured with the Selenium & Visual studio.

Q117.How screenshot are added to the failed testcases?

Screenshot should be taken in the catch block for failed testcases.

Q118.What is reporting in selenium?

All the related relevant information regarding each of the testcases must be captured and an html report should be prepared. Various external tools are available to create reporting such as Extent report, ant, maven….

Q119.Is it mandatory to call assertAll() method when comparing expected and actual result in selenium.?

It is mandatory to call assertAll() method at the end of your test when comparing expected and actual result.

If you do not use assertAll(),the test will be passed even if any assert objects throws exceptions

See the below example.

public class SoftAsserts {

 

@Test

public void userName()

{

SoftAssert s=new SoftAssert();

String eResult=”Sudeer kumar”;

String aResult=”Sudeer Raj”;

s.assertEquals(aResult, eResult);

//s.assertAll();

 

}

}

Q120.What happens when you add statements after calling “assertAll()” method when comparing the expected and actual results in selenium.?

If comparison fails, it will not execute the statements written after “assertAll()” method.

See the below example.

public class Example {

 

@Test

public void comparison()

{

SoftAssert s=new SoftAssert();

String expected=”King”;

String actual=”Queen”;

s.assertEquals(actual, expected);

s.assertAll();

//The comparison will fail so it will not execute the below statement

System.out.println(“This statement won’t be executed”);

 

}

}

Q121.How do you perform “SaveAs” operation when writing data into excel file.?

By providing different name to the excel file in the path of the file which is used as an argument for the FileOutputStream constructor.

See the below example.

public class S27_WriteDataIntoExcel

{

 

public static void main(String[] args) throws EncryptedDocumentException, IOException

{

FileInputStream fis=new FileInputStream(“D://FileOne.xlsx”);

Workbook wb = WorkbookFactory.create(fis);

Sheet sheet = wb.getSheet(“sheet1”);

//Write data into new row and new cell

sheet.createRow(1).createCell(0).setCellValue(“New Value”);

//Writing data into excel

FileOutputStream fos=new FileOutputStream(“D://FileTwo.xlsx”);

//In the above line, change the name of the file if you want to “Save As”

wb.write(fos);

 

 

 

}

 

}

Q122.How do you perform “SaveAs” operation when writing data into excel file.?

By providing different name to the excel file in the path of the file which is used as an argument for the FileOutputStream constructor.

See the below example.

public class S27_WriteDataIntoExcel

{

 

public static void main(String[] args) throws EncryptedDocumentException, IOException

{

FileInputStream fis=new FileInputStream(“D://FileOne.xlsx”);

Workbook wb = WorkbookFactory.create(fis);

Sheet sheet = wb.getSheet(“sheet1”);

//Write data into new row and new cell

sheet.createRow(1).createCell(0).setCellValue(“New Value”);

//Writing data into excel

FileOutputStream fos=new FileOutputStream(“D://FileTwo.xlsx”);

//In the above line, change the name of the file if you want to “Save As”

wb.write(fos);}}

Q123.How do u handle dynamic link without partial linkText.?

using contains () function

E.g.:  //a[contains(text(),’inbox’]

Q124.what is the difference between cssSelector and xpath.?
cssSelector xpath
Faster Slow
Browser Independent Browser dependent

 

Do not support text Support text
Do not support Group index Support Group index
/.. Not supported /.. Support

 

ancestor Not Support Ancestor Support
Q125.How do you enter the text into the current textbox or How do you find the current focused element.?

Using switchTO().activeElement();

Q126.what are the different ways of clicking on a button.?

To click on a button we can use following methods.

  • Using JavaScript Executor.
  • submit(); Method of WebElement.
  • sendKeys(Keys. Enter) Method of WebElement
  • Click(); of WebElement.
  • Robot class.

Note : Submit method can be used only if type of the button is submit or else we get NoSuchElementException.

Q127.How do you handle frames.?
  • If the element is inside the frame, then we should switch to the frame before finding the element.
  • In order to switch to the frame, we use following statement

driver. SwitchTo().frame(arg);

In the above statement frame method is overloaded. It takes an argument of type

  • int : Index which starts from 0.
  • String : id or name of the frame.
  • WebElement : Address of the frame.
Q128.Can you give a selenium example for method overloading.?

driver. SwitchTo().frame(int);

driver. SwitchTo().frame(String);

driver. SwitchTo().frame(WebElement);

Q129.How do you handle Drop down menu.?

Answer:To Handle drop down menu, we use moveToElement method of Actions Class.

Q130.How do you handle context menu.?
  • Right clicking is also called Context click.
  • If we right click anywhere on the page we see list of option which is called as Context Menu.
  • To right click we use contextClick() method of Actions Class.
  • We cannot inspect the context menu hence we select the option present in context menu by pressing the shortcuts such as T for new tab W for New Window etc.
Q131. Under which package “Actions” class is present.?

Actions class is present in interactions package.

Q132. Which method we must call whenever we call any method of actions class.?

we must call ‘perform()’ method.

Q133.what are the uses of Actions class?
  • Handling Context Menu
  • Handling Dropdown Menu
  • Drag and Drop
  • Composite action
  • Double click..Etc
Q134.Can we inspect JavaScript Pop-up.?

No

Q135.How do you handle the JavaScript Pop-up.?

To handle the JavaScript Pop-up, we use switchTo().alert() statement which will transfer the control to alert Pop-up or Confirm Pop-up. Then we use getText() method to get the message present on the pop-up. We can use accept method to click ok and we use dismiss method to click cancel.

Q136.When Hidden division pop-up is displayed.?

Hidden division pop-up is displayed when the “display” property is set to “block”

Q137.Give an example for hidden division pop-up.?

Calendar pop-up is an example for hidden division pop-up.

Q138.How do you upload the file using relative path.?

we convert relative path into absolute path using getAbsolutePath() method of file class and we use converted absolute path as argument for sendKeys() method.

Q139.When do we get invalidElementStateException.?

If the element is disabled and if we try to use SendKeys,Clear,Click methods on such element we get invalidElementStateException.

Q140.What is window handle and how to get it.?

It is the unique alphanumeric string of the browser which is generated by OS for every browser window.

To get the window handle of the browser we use the getWindowHandle method.

Example : driver.getWindowHandle();

Q141.What is the difference between getWindowHandle() and getWindowHandles().?

getWindowHandle returns window handle of current browser(string) whereas getWindowHandles returns window handle of all the browsers(Set<string>)

Q142.How do you close all the browsers without using Quit method.?

By using close() method inside For Each loop of window handles. See the below program.

public class ChildBrowserPopup

{

public static void main(String[] args)

{

System.setProperty(“webdriver.chrome.driver”,”./Drivers/chromedriver.exe”);

//Open the browser

WebDriver driver=new ChromeDriver();

driver.manage().window().maximize();

driver.get(“https://www.naukri.com/”);

 

//get the WindowHandles of all child browsers and close

Set<String> allWindows = driver.getWindowHandles();

for(String wh:allWindows)

{

driver.switchTo().window(wh).close();

}

}

}

Q143.From Which package SELECT class should be imported.?

org.openqa.selenium.support.ui.select.

Q144.How do you identify whether the list box is single select or multi select list box.?

By using isMultiple() method.

Q145.When do we get UnsupportedOperationException.?

If you apply any deselect methods of select class to single select list box, we get

“UnsupportedOperationException”.

Q146.How to get the options from the list box.?

By using getOptions() method.

Q147.What is the meaning of StaleElementReferenceException.?

It means address of the element is old.

Q148.When do we get ?

After finding the element before performing any action on that element if the page is refreshed, we get StaleElementReferenceException.

Q149.Why do we use POM pattern in selenium.?

To handle StaleElementReferenceException.

  • To maintain element repository.
  • To encapsulate the element.
  • To write the script in organized way.
Q150.If you do not use initElements() method of PageFactory class, what kind of exception do you get.?

We get NullPointerException.

Q151.What is the syntax of initializing the elements in POM class.?

PageFactory.initElements(WebDriver,POMClassObj);

E.g.:

  1. Inside POM class

PageFactory.initElements(driver,this);

  1. Inside Test class

PageFactory.initElements(driver, POMRefVar);

Q152.Will @FindBy Annotation allow us to use variable in place of locator value.?

@FindBy Annotation will not allow us to use variable in place of locator value.

Locator value should be constant(final variable or hardcoded value).

It depends on number of Rows of DataProvider array.

Q153.How do you execute ‘AutoIT’ script from Selenium?

Runtime.getRuntime().exec(“E:// AutoItCode.exe”);

Q154.If we use DataProvider How many parameters accepted by the text method.?

Depends on number of columns of DataProvider array.

Q155.How do you receive different types of data from DataProvider.?

By Changing data type of two dimensional array to object.

Q156.what is the default execution status of testNg test method.?

passed

Q157.How do you re-run failed test classes in TestNG.?

We re-run only failed test-cases using testng-failed.xml which is present inside test-out folder.

Q158.Which exception do we get if the Specified sheet name, row index or cell index is invalid while handling excel files.?

NullPointerException

Q159.How do you check whether the excel cell has string/numeric value.?

Using “getCellType()” method. If it has string, it returns “1” . If it has numeric value, it returns “0”.

Q160.How do you execute testng.xml file from pom.xml file.?

To execute TestNG.xml from POM.XML we should use a plugin and the name of the Plugin is “surefire”

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-surefire-plugin</artifactId>

<version>2.20.1</version>

<configuration>

<suiteXmlFiles>

<suiteXmlFile>testng.xml</suiteXmlFile>

</suiteXmlFiles>

</configuration>

</plugin>

 

Q161.What is the difference between Java Project and Maven Project – with respective to Automation framework.?
Sl.# Java Project Maven Project
1 We should update jar files manually Jar files will be updated automatically
2 we copy paste the jar files inside jar folder It will be downloaded under .m2/repository folder
3 The Associated Jar files will be listed under Referenced libraries Associated Jar files listed under maven dependencies
4 We execute the framework using testNG.xml  Here we execute the framework using pom.xml
5 After the execution result is stored under test-output folder After Execution result is stored under target folder.
Q162.What are the characteristic of Hidden Division Pop-up. And how do you handle it.?

Characteristics:

  • We can inspect this pop-up.
  • We cannot move this pop-up.
  • Pop-up will be in different colors.
  • It may or may not have buttons.

Solution:

  • We can handle this pop-up using ‘findElement()’ method itself. (Example for Hidden Division pop-up is ‘Calendar’)
Q163.Swap the given two numbers without using a third variable.?
public class Swapping {

public static void main(String[] args){

int n1=10;

int n2=20;

System.out.println(“Before Swapping: ” +”n1=”+n1+” “+”n2=”+n2);

n1=n1*n2;

n2=n1/n2;

n1=n1/n2;

System.out.println(“After Swapping: ” +”n1=”+n1+” “+”n2=”+n2);

}

}

Q164.Why automation testing is preferred rather than manual testing ?
  • Supports execution of regression test cases
  • Enables parallel execution
  • Improves accuracy thereby reducing human-generated errors
  • Saves time and money
Q165.What are types of testing which is supported by selenium
  • Regression
  • Functional
Q166.What is X path and its types?

X path is used to find an element of on the webpage.

The types are

  • Relative X path
  • Absolute X path
Q167.What are the tools we can use for finding X path?

The tools are

  • Chro Path
  • Xpath Finder
  • Fire Path
Q168. What are the browsers supported by selenium?

Browsers: Google chrome, IE, Mozilla Firefox, Safari, Opera etc.

Q169. What are the basic web element inputs used by automation tester?

Send keys, Click, Clear, Submit are the basic web element inputs.

Q170. How do we launch browser using web drivers?

WebDriver driver = new FirefoxDriver();
WebDriver driver = new ChromeDriver();[/togle_content] 

Q171. What are the different types of testing supported by selenium?
  • Functional
  • Regression
  • Sanity
  • Smoke
  • Responsive
  • Integration
Q172. What are the special functions used find difficult Xpath?
  • Contains
  • Sibling
  • Ancestor
Q173. What are the different components of selenium?
  • Selenium RC
  • Selenium IDE
  • Selenium Grid
  • Selenium Web driver
Q174. What are the advantages of selenium over other tools?
  • Open source
  • Free of cost
  • Language support
  • Environment support
Q175. What are the different types of exception which is commonly found in web driver?

The exceptions areTimeout exception

  • NoSuchElementException
  • ElementNotVisibleEception
Q176. What is the use of JavaScriptExecutor?

JavaScriptExecutor is commonly used as an interface to execute JavaScript through selenium web driver.

Q177. Which files can be used as data source in selenium?
  • Excel
  • XML
  • Text
  • csv
Q178. Who developed Selenium tool?

Jason Huggins and his team developed the tool in 2004 when they were working in Thought work.

Q179. What are the different ways to delay the execution in selenium?
  • Thread.sleep()
  • SetSpeed ()
Q180. What is the difference for FindElement() and FindElements()?

Find Element finds the first element within the current page. It returns only one value.

FindElements finds all the elements within the current page. It returns multiple values.

Q181. Selenium grid is a performance tool or not?

It is not a performance tool like load runner.

Q182. How would you terminate the entire program in selenium web driver?

System.exit(0);

It will help the web driver to terminate the entire java program.

Q183. What are the basic commands used for navigation in web driver?

The basic commands are

  • navigate().to()
  • navigate().refresh()
Q184. What are the basic commands used for quitting browsers?

The basic commands are

  • close()
  • quit()
Q185. Does keyboard events is possible in web driver?

Yes, it is possible. It is handled by using Advanced User Interactions API.

Q186. What are the automation tools used for functional testing ?
  • QTP
  • Selenium
  • Rational Robot
  • Coded UI
  • Auto It
Q187. What are the automation tools used for non-functional testing?
  • Load runner
  • Jmeter
  • Neoload
Q188. What is the upgrade version of selenium so far?
  • Selenium v1.0
  • Selenium v 2.0
  • Selenium v3
Q189. What is Selenese?

It is a set of commands that run your tests in selenium.

Q190. Automation tools to which can be integrated with CI/CD?

Maven, Jenkins & Docker

Q191. what do you mean by Assertion in selenium?

Assertion is state of application on which is expected.

Q192. What are the different types of wait used in selenium?
  • Implicit wait
  • Explicit wait
Q193. Different types of annotations used in selenium?

The annotations are Test, Before, After, Ignore, before class, after class, Run with

Q194. What are the web drivers supported for Mobile Testing drivers?
  • Android driver
  • I phone driver
  • OperaMobileDriver
Q195. What are the essential software for selenium?
  • Eclipse
  • JDK3
  • Selenium Libraries
Q196. What are the OS supported by selenium?

OS: Microsoft Windows, Linux, Apple OS X

Q197. What are the languages supported by browsers?

Languages: Java, C#, Python, PHP, Objective -C, Perl

Q198. How many test cases are possible to execute per day?

It depends upon the complexity and length of the test cases.2 or 3 test cases is possible.

Q199. what is the browser supported by selenium by itself?

Firefox

Q200. Open source frame work supported by selenium?
  • Junit
  • TestNG
Q201. Does deleting cookies in selenium is possible?

Yes, it is possible to delete cookies.

Driver.manage().deleteAllCookies

Q202. Compare driver.close() & driver. Quit()

Driver.close() is used to  close current web driver instance

Driver. Quit() is used to close all opened web driver instances.

Q203. Advantages of page object model
  • Code re-usability.
  • Code main ability
  • Readability
Q204. How can we scroll page up and page down?

JavaScript scrollBy() helps to scroll the document up and down.

Q205. What are the different types of waits in Selenium?

There are two types of waits in Selenium:

  • Implicit Waits
  • Explicit Waits.
Q206. What are the components in selenium?

The major components of Selenium are:

  • Selenium Webdriver
  • Selenium GRID
  • Selenium RC
  • Selenium IDE.
Q207. Does Selenium supports parallel execution?

Yes, Selenium supports parallel execution by using Selenium GRID.

Q208. Name different browsers that supports Selenium?

Google Chrome, Firefox, IE, Opera, Safari etc. are some browser that supports Selenium.

Q209. Explain the advantages and disadvantages of Selenium?

Advantages of Selenium:

  • The Selenium is free open-source and portable tool. There is no licensing cost involved for Selenium.
  • The Selenium also supports various languages which includes Java, Python, Ruby, JavaScript etc.
  • It is also compatible with various operating systems like Windows, Mac, Unix, Linux etc.
  • It can also be used across number of browsers which included internet explorer, Firefox, Google Chrome etc.

Disadvantages of Selenium:

  • The Selenium only supports web based applications. It doesn’t support desktop application.
  • It doesn’t have any tools in Selenium’s tool suite for test management.
  • There is very limited scope for image testing.
  • The new features introduced by Selenium doesn’t work properly.
  • There is lack of reliable technical support from anybody because Selenium is open-source tool.
Q210. Can we automate captcha image using selenium?

No, it is impossible to automate captcha image in selenium.

Q211. What are the different methods to send values to the textbox?

There are two different methods for sending values to the textbox.

Sendkeys()

Actions.sendkeys()

Q212. How do we handle pop up dialog in selenium?

To handle pop up dialog in Selenium you can use Alert class.

Q213. How can we handle mouse over actions in selenium?

This can be handled by using mouse over actions class.

Q214. WAP to launch the Firefox web driver?

executable_path = path of the gecko driver

Driver = webdriver.Firefox(executable_path).

Q215. Selenium supports Mobile Automation?

Selenium doesn’t supports mobile automation but you can still do it with Appium open-source test automation framework.

Q216. What is Selendroid?

The Selendroid is the test automation framework for the different types of mobile applications. This framework drives off the user interface of Android native and hybrid applications and other mobile web applications.

Q217. WAP to find the number of matches for the xpath?

By using findelemets() methods we can get number of elements for the xpath.

Q218. What is the difference between find_element and find_elements?

The major difference is that Findelement() returns one value and findelements() returns numbers of elements as the list.

Q219. How can I get alert text?

You can get alert by driver.text.

Q220. How can read the title of the page in Selenium?

You can call driver.getTitle() or driver.getPageSoruce() for reading the title of the page in Selenium.

Q221. What are the basic navigation commands in selenium?

These are the basic commands used for navigation in Selenium.

  • title
  • refresh()
  • forward()
  • back()
  • page_source
  • current_url
  • maximize_window().
Q222. What is the similarity between driver.get() and driver.navigate.to()?

Both driver.get() and driver.navigate.to() can be used for making driver.navigate faster.

Q223. Why should we choose selenium?

Selenium is one of the popular automation testing tool. This tool is used by so many companies to their product. Introduction to Selenium; Selenium is the open-source software-testing framework specially designed for the web applications. The testing performed on Selenium tool is known as Selenium testing. There is no need to learn a test scripting language (Selenium IDE) because Selenium offers record and playback tool for authoring testing.

Q224. How can we handle multiple tabs in Selenium?

Using window handlers and switch-to-method is the best way to handle multiple tabs.

Q225. What is the use of ‘System.setProperty ()’? When to use this?

System.setProperty () is used to set the path of driver executables. We can write this statement anywhere but it should be before opening the browser.

Q226. If we do not set the path of driver executables what is the exception we get?

IllegalStateException

Q227. What is ‘Up-casting’? Why we use up-casting in selenium?

Converting sub-class object to super type is called as up-casting. We do up-casting to achieve the ‘Run time Polymorphism’. In selenium we do up-casting to execute the same method or script on many browsers.

Q228. Why you up-casting to ‘WebDriver’? Why not to other interface or class?

It’s Standard in Selenium. In selenium after opening the browser we will enter the ‘URL’ using ‘get ()’ method of WebDriver interface & then we perform other cations. If we up-cast the browser object to any other interface ‘get ()’ method will be hidden & we cannot perform any other actions.

Q229. How do you find the element which is active or focused?

Using ‘switchTo().activeElement()’ statement.

Q230. How do you ‘Resize’ the browser & how do you move the browser?

Using ‘Dimension’ & ‘Point’ class.

WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
Dimension d=new Dimension(300, 400);
driver.manage().window().setSize(d);
Point p=new Point(300, 50);
driver.manage().window().setPosition(p);
Q231. What are the differences between Xpath & CSS-Selector?
  • Css-Selector is faster than X-path
  • CSS-Selector is independent on the browser whereas X-path is dependent on the browser.
  • CSS-Selector do not support ‘text()’ & ‘group Index’ whereas X-path support both.
Q232. What is Xpath axes in selenium and its use
  • Navigating from one element to another element is called as x-path traversing.
  • In order to traverse the html tree we use x-path axes.
  • Following are the very important x-path axes.
    • Child
    • Descendant
    • Parent
    • Ancestor
    • Following-sibling
    • Preceding-sibling
  • Out of all these, only first 3 has shortcuts.
    • Child is represented by                         à /
    • Descendant is represented by           à //
    • Parent is represented by                      à /..

Syntax:-  /axes :: tag

Note: After ‘tag’ we can use index, attribute, text(), contains or another axis.

Sample html:

<html>
<body>
 <table border='1'>
<tbody>
<tr>
<td>Sl.No</td>
<td>Subject</td>
<td>Cost</td>
</tr>
<tr>
<td>1</td>
<td>Java</td>
<td>7000</td>
</tr>
</tbody>
</table>
</body>
</html>

Webpage:

Sl.NoSubjectCost
1Java7000

Child à /child::html/child::body or html/body

Descendant à /descendant::a or //a

Ancestor à //tbody/../../..  (Navigating to html) or //tbody/ancestor::html

XpathMatching Elements
//td[text()=’Sl.No’]/following-sibling :: tdSubject, Cost
//td[text()=’Sl.No’]/following-sibling :: td[1]Subject
//td[text()=’Sl.No’]/following-sibling :: td[2]Cost
//td[text()=’Cost’]/preceding-sibling :: tdSubject, Sl.No
//td[text()=’Cost’]/preceding-sibling :: td[1]Subject
//td[text()=’Cost’]/preceding-sibling :: td[2]Sl.No

By using ‘getCssValue()’ method. This method is present in ‘WebElement’ interface. ‘getCssValu()’ method returns ‘String’ result. We have pass “color” argument to this method.

WebElement text=driver.findElement(By.id("headerContainer"));
                                String textColor=text.getCssValue("color");
                                System.out.println(textColor);
                                String v=Color.fromString(textColor).asHex();
                                System.out.println(v);
                                if(v.equals("#000000"))
                                {
                                                System.out.println("Color is Black");
                                }
                                else
                                {
                                                System.out.println("Color is not black");                                             
                                }
Q233. How do you find X & Y co-ordinates of an element? Write code for this?

By using ‘getLocation()’ method. To find x-value we use ‘getX()’ & for y-value ‘getY()’.This method is present in ‘WebElement’ interface & method returns ‘int’ result.

                        int x=userName.getLocation().getX();
                                int y=userName.getLocation().getY();
Q234. How do you enter value to textbox and how do you remove value from textbox without using sendKeys() & clear()? Write sample code for this?

Using JavascriptExecutor

WebDriver driver=new ChromeDriver();
                                driver.get("http://localhost:8080/login.do");
                                //Entering value to Textbox
                                String script1="document.getElementById('username').value='Vijay'";
                                JavascriptExecutor j=(JavascriptExecutor)driver;
                                j.executeScript(script1);
                                //Removing value from Textbox
                                String script2="document.getElementById('username').value=''";
                                j.executeScript(script2);
Q235. What are the uses of JavascriptExecutor?

Using JavascriptExecutor we can

  1. Scroll the page
  2. We can enter the value to a textbox. (sendKeys)
  3. We can use to remove the value present in the textbox. (clear)
  4. We can click on element.
  5. We can use to perform the action even if the element is disabled.
Q236. What are the difference between Implicit & Explicit’ Wait?
Implicit WaitExplicit Wait
1.      We do not specify the waiting condition.1.       We have to specify the waiting condition like ‘WebDriverWait.until()’
2.      We can handle synchronization of only ‘findElement’ & ‘findElements’ statements. All at a time.2.       We can handle synchronization of any statement but only one at a time.
3.      TimeUnit can be in days, hours, minutes, seconds, milliseconds, microseconds or nanoseconds.3.       TimeUnit can be only in seconds.
4.      After the specified duration we get ‘NoSuchElement’ exception.4.       After the specified duration we get ‘TimeOut’ exception.
Q237. How do you login & logout from the application without using Implicit wait, Explicit wait & Thread.Sleep() ?

We can use Custom Wait (Writing our own code)

String key="webdriver.chrome.driver";
                                String value="./Drivers/chromedriver.exe";
                                System.setProperty(key, value);
                                WebDriver driver=new ChromeDriver();
                                driver.manage().window().maximize();
                                driver.get("http://localhost:8080/login.do");// use any application’s url
                                driver.findElement(By.id("username")).sendKeys("admin");
                                driver.findElement(By.name("pwd")).sendKeys("manager");
                                driver.findElement(By.xpath("//div[.='Login ']")).click();
                                while(true)
                                {                                                try
                                                {                                                               driver.findElement(By.xpath("//a[.='Logout']")).click();

                                                                break;
                                                }
                                                catch (Exception e)
                                                {                                                             
                                                }
                                }
                                driver.close();
Q238. How do you check whether page is loaded or not within specified time?
By using ‘pageLoadTimeout()’
String key="webdriver.chrome.driver";                                
String value="./Drivers/chromedriver.exe";
                                System.setProperty(key, value);
                                WebDriver driver=new ChromeDriver();
                                driver.manage().window().maximize();
                                driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);
                                try
                                {
                                                driver.get("http://localhost:8080/login.do");
                                                System.out.println("Page Loaded in 3-Seconds");

                                }
                                catch (Exception e)
                                {
                                                System.out.println("Page is Not Loaded in 3-Seconds");
                                }
                                driver.close();
Q239.What are the different Synchronization options you have used in Selenium?
  1. Implicit Wait
  2. Explicit Wait (WebDriver Wait)
  3. Custom Wait
  4. Sleep()
  5. pageLoadTimeout()
Q240. What is ‘Composite action? How do you perform composite action in Selenium?

Performing multiple actions at a same time such as pressing multiple keys at a same time(Ctrl+c) or performing multiple actions in mouse such as ‘Click & Scroll’, ‘Click-hold-drag’ or performing one action from keyboard & another action from mouse (Ctrl+Click) all these are called as Composite actions.

This can be done using ‘Actions’ class.

//Code for Control+Click
WebElement link=driver.findElement(By.id("licenseLink"));
Actions action=new Actions(driver);
action.sendKeys(Keys.CONTROL).click(link).perform();
Q241. Write script to close all the browsers without using ‘quit()’ method?
driver.get("https://www.naukri.com/");
Set<String> allWindows = driver.getWindowHandles();
for(String wh:allWindows)
{
driver.switchTo().window(wh).close();
}
Q242. Write script to check whether specified option is present in the ListBox or not? If present check whether it’s duplicate or ot?
System.out.println("Enter the required Option");           

Scanner sc=new Scanner(System.in);               

String input = sc.nextLine();                

sc.close();                

if(map.containsKey(input))
               

 {
                                System.out.println("Option "+input+ " is present in ListBox");
                                if(map.get(input)>1)
                                

{
                                               System.out.println("Option is duplicate in ListBox");
                                }
                                else
                               

 {                                                System.out.println("Option is not duplicate");

                                }
                }                

else
                {

                                System.out.println("Option is not present in ListBox");

                }
Q243. What is the meaning of ‘StaleElementReference’ exception? When do we get this exception?

‘StaleElementReference’ exception means address (reference) of the element is old (stale). We get this exception

  • After finding element
  • If page is refreshed

Then if we try to perform the action on that element

Q244. What happens if we do not use ‘initElements()’ method of PageFactory?

We get ‘NullPointer’ exception.

Q245. How do you run ‘Test method’ multiple times without using looping statement?
By using ‘invocationCount’
public class Demo2
{
final int i=3;
@Test(invocationCount=i)
public void userName()
{
Reporter.log("My Name is Sudeer Raj”, true);
}
}

Output:

My name is Sudeer Raj

My name is Sudeer Raj

My name is Sudeer Raj

Q246. Explain the concept of Inheritance in Java and Also expalin How you implemented the concept in your project?

Inheritance concept is one where the child class extends the parent class and inherits the methods and parameters of the Parent class.

I have implemented in my project by creating a Base class and extending to all the other class so they can make use of the driver instance

Q247. What are the annotations available in TestNG? And Explain How and where you have used each of these annotations in your project

@BeforeTest

@AfterTest

@BeforeClass

@AfterClass

@BeforeMethod

@AfterMethod

@BeforeSuite

@AfterSuite

@BeforeGroups

@AfterGroups

@Test

Q248. What is Automation Testing?

Automation testing is a technique to check the software under test and compare the real outcome with the expected result using an automation tool. It automates the execution of repetitive tasks and writes test scripts without requiring the involvement of humans while executing test cases.

Q249. What are the benefits of Automation Testing?

The key benefits of using Automation Testing to test the software applications are such as:

  • Automates the manual process to test the software application
  • Executes the repetitive test cases without requiring human intervention
  • Allows user to run test cases on various machines simultaneously
  • Allows to perform functions as well as performance testing on the software
  • Increases testing efficiency and value of software application
  • Saves a lot of time because it tests application using automation tool
  • Reduces testing cost and improve accuracy
  • Reusability of tests and decrease testing efforts
Q250. Why should Selenium be selected as a test tool?

The main reasons Selenium must be chosen as a testing tool include:

  • It is open-source software and free to download and use
  • Provides large scope to test the application and find errors at an early stage
  • Compatible to run on various operating systems such as Linux, Windows and Mac operating systems
  • Compatible with multiple browsers (IE(Internet Explorer), Google Chrome, Safari, Opera Mini, etc.)
  • Supports to write test scripts in multiple languages (.Net, Python,JavaScript, Perl, Java, Ruby, etc.)
  • Provides the circulated environment to perform testing and implement test easily
Q251. Name some of the commonly used Automation Testing tools that are used for Functional Automation?

The list of popularly used automation testing tools to perform functional automation include:

  • An open-source Selenium
  • Coded User Interface
  • IBM Rational Robot
  • An open-source AutoIt software testing tool
  • HP Quick Test Professional
Q252. Name some of the commonly used Automation Testing tools that are used for Non-Functional Automation?

Some of the popularly used automation testing tools in non-functional automation include:

  • Apache JMeter
  • LoadRunner software testing tool developed by HP
  • Neoload
  • Loadtracer
  • PortSwigger BurpSuite
  • Acunetrix and Webserver Stress Tool
Q253. What are the different components of Selenium?

Selenium is an automation software testing suite package which provides a set of components to support automation across various platforms, browsers, and programming languages. It includes key elements such as:

  • Selenium WebDriver
  • Selenium RC (Remote Control)
  • Selenium IDE and Grid
Q254. What is Selenium Integrated Development Environment (Selenium IDE)?

Selenium IDE is a Firefox Plugin works based on principle record and playback that helps to record test cases and repeat to test application. It supports the tester to upload test scripts in multiple programming languages. But, it does provide portability and robustness of test scripts.

Q255. What is Selenium Remote Control (Selenium RC)?

Selenium RC is considered as a test tool enables the user to write automated User Interface (UI) tests selecting any language comfortable to them against the website. It helps to execute test cases in various browsers.

Q256. What is Selenium WebDriver?

Selenium WebDriver is a test tool that allows the tester to communicate with the web browser directly on which test scripts are executing. It uses native methods of web browser’s to automate web applications testing.

Q257. What is Selenium Grid?

Selenium Grid is a test tool allows a tester to run selenium tests across different machines in a parallel way.

Q258. List out the names of Programming Languages, Browsers & Operating Systems that are supported by Selenium?
  • Selenium supports multiple programming languages such as include JavaScript, RSpec, C#, Ruby, Java, Groovy, PHP and Perl
  • The operating systems supported by Selenium include Mac OS, Android, Windows, Solaris, and iOS
  • Selenium provides compatibility with various browsers such as IE (Internet Explorer), Firefox, Safari, Chrome, and Opera
Q259. What are the types of Testing's that are supported by Selenium?

Selenium supports various types of testing’s to test application such as

  • Interface Testing
  • Smoke Testing
  • Unit Testing
  • Regression Testing
  • Functional Testing
  • Performance Testing
  • Keyword Testing
  • Data driven and Sanity Testing
Q260. What are the Limitations of Selenium?

Selenium testing tool is limited to:

  • Perform testing on applications that are web-based only
  • Cannot perform testing on windows based applications and mobile app
  • Requires outside assistance to generate reports like Jenkins or TestNG
  • Cannot perform testing on image-based applications and does not provides built-in IDE for the generation of test scripts
  • Requires knowledge in scripting languages and Eclipse to write test scripts
Q261. What is Selenese?

Selenese is a cross-platform test scripting language used by Selenium to test web-based applications and fix bugs in software. It allows the user to develop test cases by providing a set of commands.

Q262. What is Selenium Test Scripts?

Selenium allows writing test scripts in any programming language like Selenese. Test scripts in Selenium are the set of commands.

Q263. What are the different types of locators in Selenium?

Selenium includes various types of locators such as:

  • Identifier (ID):
  • Name
  • Classname:
  • Link Text and Partial Text
  • DOM
  • CSS path
  • XPath
  • UI-element
Q264. List out some of the Automation tools which can be integrated with Selenium to achieve Continuous Integration?

The Selenium can be integrated with a list of tools to execute tests continuously include:

  • Maven
  • Jenkins
  • Docker
  • TestNG
  • JUnit
Q265. What do you mean by the assertion in Selenium?

Selenium Assertion is used to test application and compare the actual outcome with expected outcome to confirm the application is working as per expectations. There are three kinds of assertions used in Selenium include:

  1. Assert
  2. Verify
  3. WaitFor
Q266. Explain the difference between assert & verify commands?

Both commands assert and verify in Selenium are aimed to check the given element is existed on the web page or not.

Assert Command:

The Assert in Selenium is used to verify 0061 specific condition is either true or false and aborts the execution of test steps when the condition fails. When the given condition is true, it continuous test and executes next line of code.

Verify Command:

The Verify command in Selenium also used to verify a specific condition is true or false. Unlike Assert, Verify continuous the execution of test steps even the condition is failed.

Q267. What is XPath?

XPath is also known as XML path. It is an extensible markup language similar to HTML and is used to locate HTML elements across the webpage. It includes two types of strategies to locate an element on web pages such as XPath Absolute and XPath Attribute.

Q268. Explain the XPath Absolute & XPath Attribute?

XPath Absolute: It allows the users to find an absolute XPath to find an element from the root node. It starts with forwarding slash “/”.

Syntax: Html/body/tag 1[index]/tag 2[index]/tag 3[index]/…/tag N[index]

Example:html/body/div[3]/section/div[1]/div/section/div[2]/div/fieldset/form/div[2]/div/input[2]/h2[1]

XPath Attribute: It is used when there are no suitable attributes to find the path of the required elements across web page.

The syntax of XPath is followed as:

XPath = //HTMLTagName@attributename=’value n’

Here HTMLTagName is tagname of a specific node, attributename is the attribute name of node and value is attribute value.

For example: //Form[@class=’Box’]

Q269. How many types of Wait's are in Selenium?

Selenium automation includes three wait types as Implicit, Explicit, and Fluent wait type.

Implicit: This type of wait tells Selenium Web Driver to wait for a specific duration of time before throwing an exception.

Explicit: This wait type tells Selenium Web Driver to wait for a specific or expected condition before it throws an exception.

Selenium Interview Questions and Answers for Beginners

Selenium Interview Questions and Answers for Beginners

Q1. What are the different locators available in Selenium

There are 8 locators

Id , Name,  classname, cssSelector, Xpath, TagName ,Linktext and PartialLinkText

Q2. Which locators do you prefer using first?

Most Web pages have id and name properties as unique values and these should be used first for non-link items. For link items, linkText and partialLinkText are preferred. Next is Css Selector and xpath. These are least preferred because of the time taken to traverse the DOM to find elements.

Q3. What is the difference between Absolute and Relative xpath

Absolute path starts from the top of the DOM which means essentially starting from /html whereas Relative one can start from anywhere in the DOM and just matches the pattern. Also it always starts with //

Q4. What are the different exceptions in Selenium – Name 5

WaitTimeOut Exception, No Such Element, StaleElementReference, ElementNotVisible Exception and NoAlertPresent Exception

Q5. Which version of Selenium are you currently using in your project?

Selenium 3.11

Q6. What are the different kind of frameworks

Data Driven – Where same actions are performed for different sets of data and the result is verified

Keyword Driven – Commonly reused functions are stored as keywords to be used in multiple tests

Hybrid – A Mixture of Data Driven and Keyword frameworks

Q7. What are the different xpath axes

Parent::tr will get the parent of the element with the tr tag.

Ancestor – This will get any parent and not just the immediate one.

Sibling – to identify elements with the same parent. The syntax is following-sibling::tr

Q8. What is the difference between Implicit,Explicit and Fluentwait

Implicit wait is present for the entire duration of the driver instance. This is usually a small value like 5 or 10 seconds which is enough to wait for majority of the elements of the application.

Explicit wait is for elements which usually take more time to be visible than the majority of other application elements. Through the ExpectedCOnditions class, we can use many types of conditions as exit criteria for this wait.

Sample code :

WebDriverwait  wait = new WebDriverwait  (driver,10)

WebElement element = wait.until(ExpectedConditions.visibilityof(element))

Fluent wait is used when you need to add extra conditions like which exception to ignore while waiting and also specifying the polling interval

Sample code :

Wait wait2 = new FluentWait(driver)

.withTimeout(Duration.of(20, (TemporalUnit) TimeUnit.SECONDS))

.pollingEvery(Duration.of(1, (TemporalUnit) TimeUnit.SECONDS))

.ignoring(NoSuchElementException.class);

Q9. When you declare an implicit wait as X seconds, does the driver wait for X seconds for each element

No. There is a concept called polling interval which means that the driver will look into the DOM at frequent intervals. The Default value is  0.5 seconds

Q10. What is StaleElementReference Exception and when do you get it.

When an element that was present in the DOM previously but due to an user action, which results in a page refresh, the element is no longer visible on the page.

Q11. What are the ways of clicking an element apart from selenium click()

We can use javascript and actions class

((JavascriptExecutor) driver).executeScript(“arguments[0].click();”, element);

Actions ab = new Actions(driver);

ab.moveToElement(element).click();

Q12. How do you hover over an element in the Menu link to show sub menu

Actions ab = new Actions(driver);

ab.moveToElement(element);

Q13. Write code for Double click and Right Click

Actions ab = new Actions(driver);

ab.moveToElement(element).doubleClick();

ab.moveToElement(element).contextClick();

Q14. Write code for taking Screenshot

TakesScreenshot ts = (TakesScreenshot) driver

File file = ts.getScreenshotas(OutputType.FILE)

FileUtils.CopyFile(file,”//c//folder”);

Q15. What is WebDriverManager

It is a simpler way to maintain your driver executables and their versions. Instead of downloading the drivers for each browser and setting their path in the code, we can just add the WebDriverManager dependency and it will ensure the latest drivers are downloaded.

Q16. How do you get into and out of a frame

Driver.switchTo().frame(either frame id or index)

driver.switchTo().defaultContent() to move to the original node.

Q17. How do you highlight WebElements being used?

Using Javascript

((JavascriptExecutor) driver).executeScript(“arguments[0].setAttribute(‘style’,’background:yellow’);”, element);

Q18. Difference between getWindowHandle() and getWindowHandles().

getWindowHandle returns a string value that is unique and points to the current window in focus.

getWindowHandles returns a Collection(Set) of all windows opened by this driver instance.

Q19. Difference between driver.quit() and driver.close()

If there is only one window open both do the same thing. However in case of multiple windows, close closes only the focused window whereas quit closes all the windows.

Q20. Code for switching between windows – a link from main window opens another window, close it and switch to main window.

String handle1 = driver.getWindowHandle()

Driver.findElement(by.id(”some link”)).click();

Set<String> habdles = driver.getWindowHandles();

For(String s : handles){

If(s != handle1)

Driver.close();

}

Q21. Write down your Framework Structure and Explain.

Src/main/java – Contains the reusable components like BaseTest and Parent Page class, Utilities(Excel and DB Utility), Page Objects for all the pages in the application and  MainDriver script for running the tests

Src/test/java – Contains all the tests grouped under appropriate folders like Regression and Smoke.

Q22. Difference between Abstract class and Interface

Answer: An Interface can only have methods without any implementation. Since java 8 , an interface can have a method implementation with default keyword so as to enable interfaces to be flexible.

An Abstract class can have defined as well as abstract methods.

More thsn one interface can be implemented by a class whereas only one abstract class can be extended to a particular class

Q23. What are the OOPS concepts you used in your framework

Abstraction – Method implementation of reusable methods need not be shown and can be used without knowing its details.

Encapsulation – Declaring local variables as private and those which needs to be used only by extending classes or package classes as protected. The latter is useful when you add components into jars as dependency

Inheritance – BaseTest and Page class are parent classes . All test classes inherit from the former and all Page objects inherit from the latter.

Polymorphism – The same class can have different forms with different values. For example the Homepage class can have multiple instances with different values initialized in the constructor.

Q24. Is catch block mandatory?

No. Try can be followed with either catch alone or finally alone. Also try with resources does not need finally also.

Selenium with Java Interview Questions and Answers

Q1. What is Java?

Java is an High-level Object-oriented Programming language
Java is a fast, Secure ad reliable Programming language

Q2. Why is Java a platform Independent?

Java is a platform independent because it is a ‘Write once Run Anywhere’, when we compile a java program it generates a class file which can run on any system or platform.

Q3. Is java a pure Object-oriented?

No, Java is not a pure object-oriented because it makes use of eight data types which are not objects

Q4. What is a class in Java?

A class is blueprint or templatefrom which individual objects are created.

Q5. What do you mean by Object in Java?

Object is an instance of a class, which describes the state and behaviour of a class.

Q6. What is loop in java and what are the diffrent types of loops?

Loops in java are used to execute a statement or block of statement repetadely for several times.
There are 3 diffrent types of loops in Java:
a. While loop
b. do while loop
c. for loop

Q7. What are the pillars of Object-Oriented program?

Inheritance
Polymorphism
Encapsulation
Abstraction

Q8. What is Inheritance?

Inheritance is one of the pillar of the oops, which lets the sub-class or child class to inherit the properties of Base class or Parent class.

Q9. What is Polymorphism?

Polymorphism is one of the pillar of the oops, in which object has the ability to take many forms.
Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts

Q10. What is method overloading?

Method overloading is the concept of Polymorphism where a class contains multiple method with same name but diffrent types of parameters or diffrent number of parameters.

Q11. What is method overriding?

Method overriding is the concept of Pilymorphism,
In Method Overriding, child class have the same method with same name and exactly the same number and type of parameters and same return type as a super class.
It always requires inheritance in Method Overriding

Q12. What is Constructor?

Constructor in Java is used to creat an Object that is an instance of a Class. Constructor name should be same as class name. Constructor don’t have any return type hence they don’t return any value

Q13. What are local and class variables?

Local Variable:
These variables are declared inside the method and the varialbe will be destroyed once the compiler exists the method.
class Variabe:
These variables are declared inside the class but outside the method and it can be accessed any where inside the class.

Q14. What is abstraction in Java?

Abstraction is the concept of Encapsulation which hides the implementation of internal details and showing functionality to the users.

Q15. What is Encapsulation?

Encapsulation is a mechanism of binding code and data together in a single unit

Q16. What is an Array?

Array in java is used to store multiple vaules into a single variable of same data type

Q17. What are the diffrent Access modifiers availabe in Java?

Private: If the class or method or variable is declared as private it’s scope will be only with in the class
public: If the class or method or variable is declared as public it can be accessed anywhere within the class, package and outside the package
protected: If the method or variable is declared as protected it can be accessed only within a packages where it is declared

Q18. What is the difference between Array and ArrayList?

Array: Array in java is used to store multiple vaules into a single variable of same data type, once the size declared for array can’t be changed.
ArrayList: ArrayList in java is used to store multiple values into a single variable of diffrent type.

Q19. What is FileInputStream in Java?

FileInputStream is class from the java I/O package which is used to read the data from the file.

Q20. What is FileOutputStream in Java?

FileInputStream is class from the java I/O package which is used to write the data into the file.

Q21. How you handle the Exception in Java

We can handle exception in Java using try-catch block.

Q22. Write a program to print Fibonacci Series up to count 10?

public class FibonacciSeries {
public static void main(String args[]) {
int a = 0;
int b = 1;
int c;
int i;
int count = 10;
System.out.print(a);
for (i = 1; i < count; i++) {
c = a + b;
System.out.print(” ” + c);
a = b;
b = c;
}
}
}

Q23. Write a program to add two matrices?

import java.util.Scanner;
public class AddMatrix
{
public static void main(String args[])
{
int rows, cols, i, j;
Scanner in = new Scanner(System.in);
System.out.println(“Please Enter number of rows and columns”);
rows = in.nextInt();
cols = in.nextInt();
int first[][] = new int[rows][cols];
int second[][] = new int[rows][cols];
int sum[][] = new int[rows][cols];
System.out.println(“Please Enter elements of first matrix”);
for ( i = 0 ; i < rows ; i++ )
for ( j = 0 ; j < cols ; j++ )
first[i][j] = in.nextInt();
System.out.println(“Please Enter elements of second matrix”);
for ( i = 0 ; i < rows ; i++ )
for ( j = 0 ; j < cols ; j++ )
second[i][j] = in.nextInt();
for ( i = 0 ; i < rows ; i++ )
for ( j = 0 ; j < cols ; j++ )
sum[i][j] = first[i][j] + second[i][j];
System.out.println(“Sum of entered matrices:-“);
for ( i = 0 ; i < rows ; i++ )
{
for ( j = 0 ; j < cols ; j++ )
System.out.print(sum[i][j]+”\t”);
System.out.println();
}
}
}

Q24. Write a program to swap two numbers without using the third variable?

public class SwapTwoNumbers {
public static void main(String[] args) {
int num1=55;
int num2=23;
System.out.println(“Before Swapping”);
System.out.println(“Value of number1 is :” + num1);
System.out.println(“Value of number2 is :” +num2);
num1=num1+num2;
num2=num1-num2;
num1=num1-num2;
System.out.println(“After Swapping”);
System.out.println(“Value of number1 is :” + num1);
System.out.println(“Value of number2 is :” +num2);
}
}

Q25. Write a Java program to find the sum of digits?

import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
int num;
Scanner in = new Scanner(System.in);
System.out.println(“Please Enter a number”);
number=in.nextInt();
int sum=0 ;
while(num!=0){
sum=sum+(num%10);
num=num/10;
}
System.out.println(“Sum of Digits =”+sum);
}

Q26. What is Selenium?

Selenium is robust automation suite which is used for automating web based applications, It supports multiple browsers, Platforms and languages.

Q27. What are the components of Selenium?

Selenium has four components
a. Selenium IDE: Selenium IDE is a record and playback tool. It is a firefox plugin.
b. Selenium RC: Selenium RC is a server that allows a user to create test scripts in the desired programming language.
c. Selenium WebDriver: WebDriver directly communicates with the browsers using API’s
d. Selenium Grid: Selenium Grid is used to run test cases on multiple platoforms and environments concurrently.

Q28. What are the limitations of Selenium?
  1. Selenium supports only web based applications
    b. captcha and Barcode can not be automated using selenium
    c. We can generated reports only using third-party tools
Q29. What are the diffrent types of locators in Selenium?

id
name
classname
linktext
partiallinktext
cssSelector
tagname
xpath

Q30. What is the difference between ‘/’ and ‘//’ in xpath?

/ – Refers absolute xpath
// – Refers relative xpath

Q31. Why do you prefer selenium tool for automation?
  1. Free and open source
    b. Cross-brower testing
    c. Platform compatibility
    d. Supports multiple programming languages
Q32. What are soft assert and hard assert?

Soft Assert: Soft Assert does not throw any Excpetion when the assert fails the execution will continue
Hard Assert: Hard Assert throw exception when the assert fails and the execution will be terimanted.

Q33. What are the exceptions you faced in Selenium?

NoSuchElementException
WebDriverException
TimeoutException
NoAlertPresentException
NoSuchWindowException

Q34. What are the different types of waits available in Selenium?
  1. Implicit Wait: This wait tells the WebDriver to wait for certain amount of time before throwing as Exception
    driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
    b. Explicit Wait: This wait tells the WebDriver to wait for certain amount of time untill the expected condition
    WebDriverWait wait = new WebDriverWait (driver, 20);
    wait.until(ExpectedConditions.VisibilityofElementLocated(By.xpath(“”)));
    c. Fluent Wait: FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.
Q35. How to get a text of a web element?

By using the getText() method.

Q36. What is the difference between driver.get() and driver.navigate.to(“url”)?

driver.get(): To open an URL and it will wait till the whole page gets loaded
driver.navigate.to(): To navigate to an URL and It will not wait till the whole page gets loaded

Q37. What are the different types of navigation commands?

driver.navigate().forward(); – to navigate to the next web page with reference to the browser’s history
driver.navigate().back(); – takes back to the previous webpage with reference to the browser’s history
driver.navigate().refresh(); – to refresh the current web page thereby reloading all the web elements
driver.navigate().to(“url”); – to launch a new web browser window and navigate to the specified URL

Q38. How you will delete the cookies in Selenium?

driver.manage().deleteAllCookies();

Q39. How to handle multiple windows in Selenium?

Using driver.getWindowHandle() and driver.getWindowHandles() method.

Q40. What is the difference between driver.close() and driver.quit() methods?

driver.close(): This method closes the browser which is currently opened by the WebDriver.
driver.quit(): This method closes all the browser which is opened by the WebDriver.

Q41. How do you handle mousehover, doubleclick and draganddrop in Selenium?

We can handle mouseover, doubleclick and draganddrop using the Action class.
Actions action = new Actions(driver);
action.moveToElement().build().perform();
action.dragAnddrop(source, destination).build().perform();
action.doubleClick().build().perform();

Q42. What is TestNG?

TestNG is a framework which is ispired by Junit and Nunit but provides more features than these two.

Q43. What are the advantages of TestNG?
  1. TestNG provides parallel execution
    b. It allows to assign priority to test methods
    c. It allows grouping of test methods
    d. It provides the pretty HTML Reports
Q44. What are the annotations available in TestNG?

BeforeTest
AfterTest
BeforeClass
AfterClass
BeforeMethod
AfterMethod
BeforeSuite
AfterSuite
BeforeGroups
AfterGroups
Test

Q45. What is the use of testng.xml?
  1. Using testng.xml we can execute multiple test cases in one go
    b. Allows to add group dependencies
    c. Allows to parameterize the test cases
    d. Allows to execute multiple testcases on different browsers
Q46. What is cucumber?

Cucumber is a framework which is based on the Behavior Driven Development (BDD) methodology

Q47. What is feature file?

A feature file provides a high-level description. The first line of the feature file must start with the keyword ‘Feature’ following the description of the application under test.
We can include multiple secenarios in one feature file.

Q48. What are the advantages of Cucumber?
  1. Cucumber is an open source tool.
    b. Automation test cases developed using the Cucumber tool are easier to maintain
    c. Easy to integrate with other tools such as Selenium
Q49. What are the comonly used TestNG Asserts?

assertEqual
assertTrue
assertNotEqual
assertFalse

Q50. How do you set a priority of test cases in TestNG?

import org.testng.annotations.*;
public class PriorityTestCase{
@Test(priority=0)
public void testCase1() {
system.out.println(“TC 1”);
}
@Test(priority=1)
public void testCase2() {
system.out.println(“TC 2”);
}
}

Q51. Give the example of TestRunner in Cucumber?

importorg.junit.runner.RunWith;
importcucumber.api.CucumberOptions;
importcucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(features=”Features”,glue={“StepDefinition”})
public class Runner
{
}

Besant Technologies WhatsApp