8/29/18

Selenium Interview Questions and Answers


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?
SeleniumQTP
Open SourcePaid
More Add-Ons we can useLimited add-ons Only
It will support multiple browsersIt will support only Firefox, Chrome, IE
Supports different OSIt will support only Windows
It will support Mobile DevicesQTP Supports Mobile app test automation (iOS & Android) using HP solution called – HP Mobile Center
Can execute tests while the browser is minimizedNot 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’]
  1. 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
Q17How 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
Q18How 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 rows=htmltable.findElements(By.tagName(“tr”));
     Col:   List columns=rows.get(rnum).findElements(By.tagName(“th”));
Q21. How you will get the title of the page?
driver.getTtile();
Q22How 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
Q24What 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
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 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 method, then Step-2 will need to repeat.
The above steps will recur until either the timeout expires or the condition becomes true.
 Q25How 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
Q27Why 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”);

29. How to handle 2 windows or explain window handling.
driver.getWindowHandle();  – Single Window
       driver.getWindowHandles();  – Multiple windows
Q30Difference between ANT and MAVEN?
AntMaven
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
Q32How 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.
Q35How 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
Q37What 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:

   
     
     
     
   
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
 Q41Firefox 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?
JExcelApache POI
It doesn’t support Excel 2007 and Xlsx format. It supports only Excel 2003 and .Xls formatIt supports both
JXL doesn’t support Conditional formattingIt supports
JXL API was last updated in 2009Apache POI is actively maintained
It doesn’t support rich text formattingApache POI supports it
It has very less documents and examples as compare to Apache POIIt 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
Q49Which is more preferable xpath or CSS?
CSS Selector
Q50. How  to find out all the links in webpage?
List allLinks = driver.findElements(By.tagName(“a”));
Q51How we will configure the Parallel browser testing in testng.xml?
 Q52Explain 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.png”        
    FileUtils.copyFile(scrFile, new File(“D:\\screenshot.png”));
Q54How to find out all the frames in a webpage?
List ele = driver.findElements(By.tagName(“frame”));
     System.out.println(“Number of frames in a page :” + ele.size());
Q55How 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
 Q56What 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:
  1. Hard Assert
  2. 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
61. 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.
  1. 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.
  2. There is single repository for the services or operations offered by the page rather than having these services scattered throughout the tests.
Q62What is the default port for selenium Grid?
      The default port used by the hub is 4444
Q63. Selenium advantages and disadvantages?
Advantages:
  1. Selenium is pure open source, freeware and portable tool.
  2. Selenium supports variety of languages that include Java, Perl, Python, C#, Ruby, Groovy, Java Script, and VB Script. etc.
  3. Selenium supports many operating systems like Windows, Macintosh, Linux, Unix etc.
  4. Selenium supports many browsers like Internet explorer, Chrome, Firefox, Opera, Safari etc.
  5. Selenium can be integrated with ANT or Maven kind of framework for source code compilation.
  6. Selenium can be integrated with TestNG testing framework for testing our applications and generating reports.
  7. Selenium can be integrated with Jenkins or Hudson for continuous integration.
  8. Selenium can be integrated with other open source tools for supporting other features.
  9. Selenium can be used for Android, IPhone, Blackberry etc. based application testing.
  10. Selenium supports very less CPU and RAM consumption for script execution.
  11. Selenium comes with different component to provide support to its parent which is Selenium IDE, Selenium Grid and Selenium Remote Control (RC).
Disadvantages:
  1. Selenium needs very much expertise resources. The resource should also be very well versed in framework architecture.
  2. Selenium only supports web based application and does not support windows based application.
  3. It is difficult to test Image based application.
  4. Selenium need outside support for report generation activity like dependence on TestNG or Jenkins.
  5. Selenium does not support built in add-ins support.
  6. Selenium user lacks online support for the problems they face.
  7. Selenium does not provide any built in IDE for script generation and it need other IDE like Eclipse for writing scripts.
  8. Selenium Automation Engineers are bit in scarcity these days.
  9. Selenium script creation time is bit high.
  10. Selenium does not support file upload facility.
  11. 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:
  1. selectByValue()
  2. selectByVisibleText()
  3. 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:
  1. Internet speed
  2. Server response time
  3. System configuration
To avoid the timing errors(Synchronization errors) between the tool (webdriver) and application, we take the help of Synchronization commands.
  1. Implicit Wait: It is used to define wait for all the elements of WebDriver.
Syntax:
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  1. 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:
  1. driver.get(“URL”);
  2. driver.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?
  1. Bitmap comparison Is not possible using Selenium WebDriver
  2. Automating Captcha is not possible using Selenium WebDriver
  3. We can not read barcode using Selenium WebDriver
  4. 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.
Q107What is the default port used by Node in Selenium Grid?
The default port used by the Node is 5555

0 comments:

Post a Comment