What is Automation Testing?
Automation testing is the process of testing the software using an automation tool to find the defects. In this process, executing the test scripts and generating the results are performed automatically by automation tools. Some most popular tools to do automation testing are HP QTP/UFT, Selenium WebDriver, etc.,
What are the benefits of Automation Testing?
· Saves time and money. Automation testing is faster in execution.
· Reusability of code. Create one time and execute multiple times with less or no maintenance.
· Easy reporting. It generates automatic reports after test execution.
· Easy for compatibility testing. It enables parallel execution in the combination of different OS and browser environments.
· Low-cost maintenance. It is cheaper compared to manual testing in a long run.
· Automated testing is more reliable.
· Automated testing is more powerful and versatile.
· It is mostly used for regression testing. Supports execution of repeated test cases.
· Minimal manual intervention. Test scripts can be run unattended.
· Maximum coverage. It helps to increase the test coverage.
What type of tests have you automated?
Our main focus is to automate test cases to do Regression testing, Smoke testing, and Sanity testing. Sometimes based on the project and the test time estimation, we do focus on End to End testing.
What is Page Object Model?
Page Object Model (POM) is a design pattern, popularly used in test automation that creates Object Repository for web UI elements. The advantage of the model is that it reduces code duplication and improves test maintenance.
Under this model, for each web page in the application, there should be a corresponding Page Class. This Page class will identify the WebElements of that web page and also contains Page methods which perform operations on those WebElements. Name of these methods should be given as per the task they are performing, i.e., if a loader is waiting for the payment gateway to appear, POM method name can be waitForPaymentScreenDisplay().
Advantages of POM
- Page Object Design Pattern says operations and flows in the UI should be separated from verification. This concept makes our code cleaner and easy to understand.
- The Second benefit is the object repository is independent of test cases, so we can use the same object repository for a different purpose with different tools. For example, we can integrate Page Object Model in Selenium with TestNG/JUnit for functional Testing and at the same time with JBehave/Cucumber for acceptance testing.
- Code becomes less and optimized because of the reusable page methods in the POM classes.
- Methods get more realistic names which can be easily mapped with the operation happening in UI. i.e. if after clicking on the button we land on the home page, the method name will be like 'gotoHomePage()'.
What is Page Factory in Selenium?
Page Factory in Selenium is an inbuilt Page Object Model framework concept for Selenium WebDriver but it is very optimized. It is used for initialization of Page objects or to instantiate the Page object itself. It is also used to initialize Page class elements without using "FindElement/s."
Here as well, we follow the concept of separation of Page Object Repository and Test Methods. Additionally, with the help of class PageFactory in Selenium, we use annotations @FindBy to find WebElement. We use initElements method to initialize web elements
How many test cases you have automated per day?
It depends on Test case scenario complexity and length. I did automate 2-5 test scenarios per day when the complexity is limited. Sometimes just 1 or fewer test scenarios in a day when the complexity is high.
5. What is a Framework?
A framework defines a set of rules or best practices which we can follow in a systematic way to achieve the desired results. There are different types of automation frameworks and the most common ones are:
• Data Driven Testing Framework
• Keyword Driven Testing Framework
• Hybrid Testing Framework
6. Have you created any Framework?
If you are a beginner: No, I didn’t get a chance to create a framework. I have used the framework which is already available.
If you are an experienced tester: Yes, I have created a framework. Or I have involved in the creation of the framework.
7. Can you explain the Framework which you have used in your Selenium Project?
Here we have clearly explained each component of Framework.
8. Why do you prefer Selenium Automation Tool?
· Free and open source
· Have large user base and helping communities
· Cross browser compatibility
· Platform compatibility
· Multiple programming languages support
9. What is Selenium?
Selenium is an open source (free) automated testing suite to test web applications. It supports different platforms and browsers. It has gained a lot of popularity in terms of web-based automated testing and giving a great competition to the famous commercial tool HP QTP (Quick Test Professional) AKA HP UFT (Unified Functional Testing).
Selenium is a set of different software tools. Each tool has a different approach in supporting web based automation testing.
It has four components namely,
i Selenium IDE (Integrated Development Environment)
ii Selenium RC (Remote Control) – selenium 1
iii Selenium WebDriver – selenium 2 & 3
iv Selenium Grid
10. What is Selenium IDE?
Selenium IDE (Integrated Development Environment) is a Firefox plugin. It is the simplest framework in the Selenium Suite. It allows us to record and playback the scripts. Even though we can create scripts using Selenium IDE, we need to use Selenium RC or Selenium WebDriver to write more advanced and robust test cases.
11. What is Selenese?
Selenese is the language which is used to write test scripts in Selenium IDE.
12. Which is the only browser that supports Selenium IDE to be used?
Firefox
13. What is Selenium RC?
Selenium RC AKA Selenium 1. Selenium RC was the main Selenium project for a long time before the WebDriver merge brought up Selenium 2. Selenium 1 is still actively supported (in maintenance mode). It relies on JavaScript for automation. It supports Java, Javascript, Ruby, PHP, Python, Perl and C#. It supports almost every browser out there.
14. What is Selenium WebDriver?
Selenium WebDriver AKA Selenium 2 is a browser automation framework that accepts commands and sends them to a browser. It is implemented through a browser-specific driver. It controls the browser by directly communicating with it. Selenium WebDriver supports Java, C#, PHP, Python, Perl, Ruby.
15. What is Selenium Grid?
Selenium Grid is a tool used together with Selenium RC to run tests on different machines against different browsers in parallel. That is, running multiple tests at the same time against different machines running different browsers and operating systems.
In simple words, it is used to distribute your test execution on multiple platforms and environments concurrently.
16. When do you use Selenium Grid?
Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers concurrently so as to achieve distributed test execution
17. What are the advantages of Selenium Grid?
It allows running test cases in parallel thereby saving test execution time.
It allows multi-browser testing
It allows us to execute test cases on multi-platform
18. What is a hub in Selenium Grid?
A hub is a server or a central point that controls the test executions on different machines.
19. What is a node in Selenium Grid?
Node is the machine which is attached to the hub. There can be multiple nodes in Selenium Grid.
20. What are the types of WebDriver APIs available in Selenium?
• Firefox Driver
• Gecko Driver
• InternetExplorer Driver
• Chrome Driver
• HTMLUNIT Driver
• Opera Driver
• Safari Driver
• Android Driver
• iPhone Driver
• EventFiringWebDriver
21. Which WebDriver implementation claims to be the fastest?
The fastest implementation of WebDriver is the HTMLUnitDriver. It is because the HTMLUnitDriver does not execute tests in the browser.
22. What are the Programming Languages supported by Selenium WebDiver?
• Java
• C#
• Python
• Ruby
• Perl
• PHP
23. What are the Operating Systems supported by Selenium WebDriver?
• Windows
• Linux
• Apple
24. What are the Open-source Frameworks supported by Selenium WebDriver?
• JUnit
• TestNG
• CUCUMBER
• JBHEAVE
25. What are the Locators available in Selenium?
Different types of locators are:
1 ID –
2 ClassName –
3 Name –
4 TagName –
5 LinkText –
6 PartialLinkText –
7 XPath –
8 CSS Selector –
26. What is a XPath?
XPath is used to locate the elements. Using XPath, we could navigate through elements and attributes in an XML document to locate web elements such as textbox, button, checkbox, Image etc., in a web page.
27. What is the difference between “/” and “//”
Single Slash “/” – Single slash is used to create XPath with absolute path i.e. the XPath would be created to start selection from the document node/start node
Double Slash “//” – Double slash is used to create XPath with relative path i.e. the XPath would be created to start selection from anywhere within the document.
28. What is the difference between Absolute Path and Relative Path?
Absolute XPath starts from the root node and ends with desired descendant element’s node. It starts with top HTML node and ends with input node. It starts with a single forward slash(/) as shown below.
/html/body/div[3]/div[1]/form/table/tbody/tr[1]/td/input
Relative XPath starts from any node in between the HTML page to the current element’s node(last node of the element). It starts with a single forward slash(//) as shown below.
//input[@id=’email’]
29. What is the difference between Assert and Verify in Selenium?
1
2
3
4
5
WebDriver driver = new FirefoxDriver();
instead of creating
FirefoxDriver driver = new FirefoxDriver();
1
driver.findElement(By.linkText(“Software Testing Material Website”)).click();
1
1
driver.get(“http://www.softwaretestingmaterial.com”);
3 1
4 boolean elePresent = driver.findElement(By.xpath(“xpath”)).isDisplayed();
3 1
4 boolean eleSelected= driver.findElement(By.xpath(“xpath”)).isSelected();
3 1
4 boolean eleEnabled= driver.findElement(By.xpath(“xpath”)).isEnabled();
Assert: In simple words, 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: In simple words, there won’t be any halt in the test execution even though the verify condition is true or false.
For detailed post check the below link.
30. What are Soft Assert and Hard Assert in Selenium?
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
Hard Assert: Hard Assert throws an AssertException immediately when an assert statement fails and test suite continues with next @Test
31. What are the verification points available in Selenium?
In Selenium IDE, we use Selenese Verify and Assert Commands as Verification points
In Selenium WebDriver, there is no built-in features for verification points. It totally depends on our coding style. some of the Verification points are
To check for page title
To check for certain text
To check for certain element (text box, button, drop down, etc.)
32. How to launch a browser using Selenium WebDriver?
WebDriver is an Interface. We create Object of a WebDriver Interface.
<2.53 – no geckodriver
3.x – geckodriver for FF
To launch Firefox Driver:
WebDriver driver = new FirefoxDriver();
To launch Chrome Driver:
WebDriver driver = new ChromeDriver();
To launch Internet Explorer Driver:
WebDriver driver = new InternetExplorerDriver();
33. Is the FirefoxDriver a Class or an Interface?
FirefoxDriver is a Java class, and it implements the WebDriver interface.
34. What is the super interface of WebDriver?
SearchContext.
35. Explain the line of code Webdriver driver = new FirefoxDriver(); ?
‘WebDriver‘ is an interface and we are creating an object reference of type WebDriver instantiating an object of FirefoxDriver class.
36. We do create a reference variable ‘driver’ of type WebDriver
WebDriver driver = new FirefoxDriver();
instead of creating
FirefoxDriver driver = new FirefoxDriver();
What is the purpose of doing this way?
f we create a reference variable driver of type WebDriver then we could use the same driver variable to work with any browser of our choice such as IEDriver, SafariDriver etc.,
//FirefoxDriver driver = new FirefoxDriver();
ChromeDriver driver = new ChromeDriver();
driver.get(“http://www.google.com”);
WebDriver driver = new FirefoxDriver();
37. What are the different exceptions you have faced in Selenium WebDriver?
• WebDriverException
• TimeoutException
• NoAlertPresentException
• NoSuchWindowException
• NoSuchElementException
• StaleElementReferenceException
• IllegalStateException
38. How To Login Into Any Site If It Is Showing Any Authentication Pop-Up For Username And Password?
To do this we pass username and password with the URL
http://username:password@url
e.g. http://admin:admin123@xyz.com
39. What are the types of waits available in Selenium WebDriver?
In Selenium we could see three types of waits such as Implicit Waits, Explicit Waits and Fluent Waits.
• Implicit Waits –
• Explicit Waits –
• Fluent Waits –
• PageLoadTimeOut
• Thread.sleep() – static wait
40. What is Implicit Wait In Selenium WebDriver?
Implicit waits tell to the WebDriver to wait for a certain amount of time before it throws an exception. Once we set the time, WebDriver will wait for the element based on the time we set before it throws an exception. The default setting is 0 (zero). We need to set some wait time to make WebDriver to wait for the required time.
41. What is WebDriver Wait In Selenium WebDriver?
WebDriverWait is applied on a certain element with defined expected condition and time. This wait is only applied to the specified element. This wait can also throw an exception when an element is not found.
42. What is Fluent Wait In Selenium WebDriver?
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.
43. How to input text in the text box using Selenium WebDriver?
By using sendKeys() method
WebDriver driver = new FirefoxDriver();
driver.get(“https://www.gmail.com”);
driver.findElement(By.xpath(“xpath”)).sendKeys(“test”);
44. How to input text in the text box without calling the sendKeys()?
// To initialize js object
JavascriptExecutor JS = (JavascriptExecutor)driver;
// To enter username
JS.executeScript(“document.getElementById(‘User’).value=test.com'”);
45. How to clear the text in the text box using Selenium WebDriver?
By using clear() method
WebDriver driver = new FirefoxDriver();
driver.get(“https://www.gmail.com”);
driver.findElement(By.xpath(“xpath_of_element1”)).sendKeys(“Software Testing Material Website”);
driver.findElement(By.xpath(“xpath_of_element1”)).clear();
46. How to get a text of a web element?
By using getText() method
47. How to get an attribute value using Selenium WebDriver?
By using getAttribute(value);
48. How to click on a hyperlink using Selenium WebDriver?
We use click() method in Selenium to click on the hyperlink
driver.findElement(By.linkText(“Software Testing Material Website”)).click();
49. How to submit a form using Selenium WebDriver?
We use “submit” method on element to submit a form
driver.findElement(By.id(“form_1”)).submit();
Alternatively, you can use click method on the element which does form submission
50. How to press ENTER key on text box In Selenium WebDriver?
To press ENTER key using Selenium WebDriver, We need to use Selenium Enum Keys with its constant ENTER.
driver.findElement(By.xpath(“xpath”)).sendKeys(Keys.ENTER);
51. How to pause a test execution for 5 seconds at a specific point?
By using java.lang.Thread.sleep(long milliseconds) method we could pause the execution for a specific time. To pause 5 seconds, we need to pass parameter as 5000 (5 seconds)
Thread.sleep(5000)
52. Is Selenium Server needed to run Selenium WebDriver Scripts?
When we are distributing our Selenium WebDriver scripts to execute using Selenium Grid, we need to use Selenium Server.
53. What happens if I run this command. driver.get(“www.softwaretestingmaterial.com”) ;
An exception is thrown. We need to pass HTTP protocol within driver.get() method.
driver.get(“http://www.softwaretestingmaterial.com”);
54. What is the alternative to driver.get() method to open an URL using Selenium WebDriver?
Alternative method to driver.get(“url”) method is driver.navigate.to(“url”)
55. 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.get(): To navigate to an URL and It will not wait till the whole page gets loaded
56. Can I navigate back and forth in a browser in Selenium WebDriver?
We use Navigate interface to do navigate back and forth in a browser. It has methods to move back, forward as well as to refresh a page.
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
57. What are the different types of navigation commands?
Refer above question (Can I navigate back and forth in a browser)
58. How to fetch the current page URL in Selenium?
To fetch the current page URL, we use getCurrentURL()
driver.getCurrentUrl();
59. How can we maximize browser window in Selenium?
To maximize browser window in selenium we use maximize() method. This method maximizes the current window if it is not already maximized
driver.manage().window().maximize();
60. How to delete cookies in Selenium?
To delete cookies we use deleteAllCookies() method
driver.manage().deleteAllCookies();
61. What are the ways to refresh a browser using Selenium WebDriver?
There are multiple ways to refresh a page in selenium
• Using driver.navigate().refresh() command as mentioned in the question 45
• Using driver.get(“URL”) on the current URL or using driver.getCurrentUrl()
• Using driver.navigate().to(“URL”) on the current URL or driver.navigate().to(driver.getCurrentUrl());
• Using sendKeys(Keys.F5) on any textbox on the webpage
62. What is the difference between driver.getWindowHandle() and driver.getWindowHandles() in Selenium WebDriver?
driver.getWindowHandle() – It returns a handle of the current page (a unique identifier)
driver.getWindowHandles() – It returns a set of handles of the all the pages available.
63. What is the difference between driver.close() and driver.quit() methods?
Purpose of these two methods (driver.close and driver.quit) is almost same. Both allow us to close a browser but still, there is a difference.
driver.close(): To close current WebDriver instance
driver.quit(): To close all the opened WebDriver instances
64. What is the difference between driver.findElement() and driver.findElements() commands?
The difference between driver.findElement() and driver.findElements() commands is-
• findElement() returns a single WebElement (found first) based on the locator passed as parameter. Whereas findElements() returns a list of WebElements, all satisfying the locator value passed.
• Syntax of findElement()-
• WebElement textbox = driver.findElement(By.id(“textBoxLocator”));
• Syntax of findElements()-
• List <WebElement> elements = element.findElements(By.id(“value”));
• Another difference between the two is- if no element is found then findElement() throws NoSuchElementException whereas findElements() returns a list of 0 elements.
List<WebElement> list = driver.findElements(By.tagName(“a”));
Sop(list.size()); ==40
65. How to find whether an element is displayed on the web page?
WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels etc.
1 isDisplayed()
2 boolean elePresent = driver.findElement(By.xpath(“xpath”)).isDisplayed();
1 isSelected()
2 boolean eleSelected= driver.findElement(By.xpath(“xpath”)).isSelected();
1 isEnabled()
2 boolean eleEnabled= driver.findElement(By.xpath(“xpath”)).isEnabled();
66. How to select a value in a dropdown?
By using Select class
WebElement mySelectElement = driver.findElement(By.name(“dropdown”));
Select dropdown = new Select(mySelectElement);
dropdown.selectByVisibleText(Text);
dropdown.selectByIndex(Index);
dropdown.selectByValue(Value);
67. How to capture Screenshot in Selenium WebDriver?
By using TakesScreenshot Interface
In Selenium 3, we may face few issues while capturing Screenshots. To overcome we use aShot utility. Click on below links to see posts related to the normal way of capturing a screenshot and capturing a screenshot using aShot utility.
68. How to mouse hover on a web element using WebDriver?
By using Actions class
WebElement ele = driver.findElement(By.xpath(“xpath”));
//Create object ‘action’ of an Actions class
Actions action = new Actions(driver);
//Mouseover on an element
action.moveToElement(ele).build().perform();
69. How can we handle web based pop-up?
To handle alerts popups we need to do switch to the alert window and call Selenium WebDriver Alert API methods.
70. How can we handle windows based pop up?
Selenium doesn’t support windows based applications. It is an automation testing tool which supports only web application testing. We could handle windows based popups in Selenium using some third party tools such as AutoIT, SIKULI, Robot class etc.
71. How to handle hidden elements in Selenium WebDriver?
It is one of the most important selenium interview questions.
We can handle hidden elements by using javaScript executor
(JavascriptExecutor(driver)).executeScript(“document.getElementsByClassName(ElementLocator).click();”);
72. How can you find Broken Links in a page using Selenium WebDriver?
73. How to find more than one web element in the list?
// To store the list
List <WebElement> eleList = driver.findElements(By.xpath(“xpath”));
// To fetch the size of the list
int listSize = eleList.size();
//for loop
for (int i=0; i<listSize; i++)
{
// Clicking on each link
links.get(i).click();
// Navigating back to the previous page that stores the links
driver.navigate().back();
}
74. How to read a JavaScript variable in Selenium WebDriver?
By using JavascriptExecutor
// To initialize the JS object.
JavascriptExecutor JS = (JavascriptExecutor) webdriver;
// To get the site title.
String title = (String)JS.executeScript(“return document.title”);
System.out.println(“Title of the webpage : ” + title);
75. How do you read test data from excels?
Test data can efficiently be read from excel using JXL or POI API. POI API has many advantages than JXL.
76. Is it possible to automate the captcha using Selenium?
No, It’s not possible to automate captcha and bar code reader.
77. 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 bar code using Selenium WebDriver
4. windows OS based pop ups
5. third party calendars/element
6. Image
7. Word/PDF
78. What is Object Repository in Selenium WebDriver?
Object Repository is used to store element locator values in a centralized location instead of hard coding them within the scripts. We do create a property file (.properties) to store all the element locators and these property files act as an object repository in Selenium WebDriver.
79. How can you use the Recovery Scenario in Selenium WebDriver?
By using “Try Catch Block” within Selenium WebDriver Java tests.
try {
driver.get(“www.xyz.com”);
}catch(Exception e){
System.out.println(e.getMessage());
}
80. How to Upload a file in Selenium WebDriver?
There are two cases which are majorly used to upload a file in Selenium WebDriver such as using SendKeys Method and using AutoIT Script.
Browser Button – type =“file”
SendKeys (c:\test\naveen.jpg);
81. How to Download a file in Selenium WebDriver?
By using AutoIT script, we could download a file in Selenium WebDriver.
82. How to run Selenium WebDriver Test from the command line?
Class A{
}
cd c
c: javac A.java
c: java A.java
java org.testng.TestNG C:Users Desktop workspacetestingtestng.xml
83. How to switch between frames in Selenium?
By using the following code, we could switch between frames.
driver.switchTo().frame();
84. How to connect a Database in selenium?
As we all know Selenium WebDriver is a tool to automate User Interface. We could only interact with Browser using Selenium WebDriver.
We use JDBC Driver to connect the Database in Selenium (While using Java Programming Language).
85. How To Resize Browser Window Using Selenium WebDriver?
To resize the browser window to particular dimensions, we use ‘Dimension’ class to resize the browser window.
//Create object of Dimensions class
Dimension d = new Dimension(480,620);
//Resize the current window to the given dimension
driver.manage().window().setSize(d);
86. How To Scroll Web Page Down Or UP Using Selenium WebDriver?
JavaScript scrollBy() method scrolls the document by the specified number of pixels.
87. How To Perform Right Click Action (Context Click) In Selenium WebDriver?
We use Actions class in Selenium WebDriver to do Right-Click (Context Click) action.
action.contextClick(driver.findElement(By.xpsjht()).build().perform();
88. How To Perform Double Click Action In Selenium WebDriver?
We use Actions class to do Double click action in selenium.
89. How To Perform Drag And Drop Action in Selenium WebDriver?
We use Actions class to do Drag And Drop Action
90. How To Highlight Element Using Selenium WebDriver?
By using JavascriptExecutor interface, we could highlight the specified element
91. Challenges faced using selenium automation testing, and how to solve them
1. Image or text overlapping issue
2. No facility to deal with Captcha, Bar Code
3. Doesn’t support any non web based (Like Win 32, Java Applet, Java Swing, .Net Client Server etc) applications
4. When you compare selenium with QTP, Silk Test, Test Partner and RFT, there are many challenges in terms of maintainability of the test cases
5. Since Selenium is a freeware tool, there is no direct support if one is in trouble with the support of applications
6. Bitmap comparison is no t supported by Selenium
7. Any reporting related capabilities, you need to depend on third party tools
8. You need to learn any one of the native language like (.Net, Java, Perl, Python, PHP, Ruby) to work efficiently
9. Difficult to identify dynamic objects
10. Working with frames
11. Selenium test playback is slow (IDE)
12. JavaScript sandbox, Flash, Applets, Silverlight, and HTML 5’s Canvas all present problems in Selenium
13. 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.
14. Timeout resulting from synchronization problems: One should ideally use selenium.IsElementPresent(locator) to verify that the object is in a loop with Thread.Sleep
15. 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.
16. Unexpected error launching Internet Explorer. Browser zoom level should be set to 100% by default for the IE browser to overcome this error
17. Protected Mode must be set to the same valueerror 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
18. Cross Browser Testing Issues
19. Ajax Components
Why are assertions important in Selenium? What are different types of assertions?
Assertions are important for validation. They clearly state whether or not a test case is behaving as expected. As a regression suite or sanity suite, for instance, runs for a long duration, it is not always possible to sit in front of the system and look at the execution. Assertions help testers mark test cases as passed or failed.
There are 2 types of assertions:
1. Soft assert
This type of assertion will just verify the condition and give the result, but it won’t abort the test case execution when the test case fails.
2. Hard Assert
This type of assertion checks for the expected result, and if the condition fails to match, it will abort execution and throw the “java.lang.AssertionError” exception.
The different types of hard assertions in Selenium are:
assertEquals()
assertNotEquals()
assertNull()
assertNotNull()
assertTrue()
assertFalse()
What is the need of database automation testing? Is it possible to perform database testing with Selenium?
Currently, the amount of data being generated and used is increasing by the day. Moreover, with advanced front ends, back ends need to be more robust and detailed. Databases play a major role in storing and sequencing data.
– Defect-free data processing
– ACID properties validation (ACID means Atomicity, Consistency, Isolation and Durability)
– Accurate storage and retrieval of values in and from the database
– Data integrity and proper data mapping
– Bugs that cannot be found in front-end testing are brought to light
Yes, it’s possible to do database testing with Selenium. First you need to make a connection between the server and the database. To do so you need a JDBC connection. JDBC is an SQL-based Java API that allows for connectivity between the Java programming language and various databases. With JDBC it is possible to connect with the database and execute queries. Once these two steps are done, one can process the results. Key components of JDBC are:
1. Driver manager
2. Driver
3. Connection
The syntax to connect with the database is:
DriverManager.getConnection(URL, “userid”, “password” )
Similarly, the code to load the JDBC driver is:
Class.forName(“com.mysql.jdbc.Driver”);
To send queries to the database one can use the Statement object. Similarly, to process the data one can use a getXXX() method.
Is it possible to do responsive web design testing using Selenium?
Responsive web design testing is important, since many users use smartphones or tabs, and not just laptops, to access applications. Manually testing the application across all the platforms would entail a cumbersome and time-consuming task, which could potentially delay releases. To automate RWD testing one can use the Galen Framework. This add-on runs in Selenium Grid and with it one can run parallel tests as well as have the tests run in a cloud.
For visual validations, one can do RWD testing with Ocular library. Similarly, WAVE Evaluator can be used for check compliance with accessibility standards automatically.
What is the difference between ChromeOptions and DesiredCapabilities?
ChromeOptions is a class that can be used to manipulate capabilities specific to ChromeDriver. For instance, you can disable Chrome extensions with:
ChromeOptions options = new ChromeOptions()
options.addArgument(“disable-extensions”);
ChromeDriver driver = new ChromeDriver(options);
DesiredCapabilities can also be used to manipulate a ChromeDriver session. To change individual web driver properties, DesiredCapabilities class provides key-value pairs.
But, ChromeOptions supports limited clients whereas DesiredCapabilities supports a vast number of clients. ChromeOptions is supported by Java and other languages. DesiredCapabilities is available in Java, but its use is deprecated. When working with a client library, like Selenium Ruby Client, the ChromeOption class will not be available and DesiredCapabilities will have to be used.
DesiredCapabilities are commonly used with Selenium Grid, for parallel execution of test cases on different browsers. However, one can use both DesiredCapabilities and ChromeOptions using merge:
DesiredCapabilities capabilities = new DesiredCapabilities();
options = new ChromeOptions();
options.merge(capabilities);
driver = new ChromeDriver(options);
How to handle an Authentication Pop-up using Selenium WebDriver?
As IT is rapidly changing, likewise, applications must be more secure. So, many companies have their own proxy settings for applications. If you open their server in a browser, it will ask you to enter the credentials. Even Selenium needs to handle the same auth pop-up before accessing the server.
Here are 3 ways how you can do that.
– Via the URL
Here, one is passing the username and password via the URL.
The syntax is: http://username:password@URL
For example,
Username: rohit
Password: P@ssword
URL: www.myurl.com
String URL = “http://” + rohit + ”:” + P@ssword + “@” + www.myurl.com;
driver.get(URL);
Alert alert = driver.switchTo().alert();
alert.accept();
– Using AutoIT
Sample AutoIT script,
WinWaitActivate(“Authentication Required”,””)
Send(“rohit{TAB}P@ssword{ENTER}”)
The AutoIT script would be passed within the Java code
– With Alerts
One can handle auth pop-ups with alerts with,
driver.switchTo().alert();
//WebDriver Java Code for entering Username and Password
driver.findElement(By.id(“userID”)).sendKeys(“userName”);
driver.findElement(By.id(“password”)).sendKeys(“myPassword”);
driver.switchTo().alert().accept();
driver.switchTo().defaultContent();
In case passing by URL does not work, one can also obtain credentials by Chrome extensions and driver.
When does Implicitly Wait is applicable for findElements method.?
Implicit wait in selenium is applicable for all findElement statements, but the applicability of implicit wait to the findElements is Limited.
Implicitly wait is applicable on findElements only when there are no elements present, selenium webdriver moves to next command the moment it finds a single element.
If there is Zero matching elements selenium waits till the time it reaches provided implicitly wait
Scenario 1 : Consider a page having 100 checkboxes and applied implicit wait is 30 Seconds
When the page is loading, selenium tries to find all the matching elements, but at that moment, there no matching elements.
After 10 seconds of wait 1 checkbox is loaded, now selenium finds that one checkbox and concludes that there is only one element, so it ends the wait and moves to the next command.
Selenium does not wait till 100 checkboxes loaded into the page, as the webdriver does not know how many elements going to be present on the page.
Scenario 2 : Consider a page having 0 checkboxes and applied implicit wait is 30 Seconds
Selenium tries to find all the matching elements in DOM, but so far, no checkbox is loaded.
Now there are zero matches, so selenium waits till 30 seconds, and if does not find element after 30 seconds selenium webdriver throws NoSuchElementEXception
How do you check an option is present in a dropdown or not ?
Answer 1 : Find the dropdown and Create an object to the Select class and Retrieve all options using getOptions() method and Iterate all options and compare the text.
Answer 2 : Find the dropdown and create the object to Select class and try to select the option using selectByVisibleText, if the option is there, then it will be selected; otherwise, it will throw an exception. So based on this exception, we can decide whether the element is there or not.
Answer 3 : Write the XPath/CSS which matches all the options(//select/option) inside the dropdown and get InnerHtml (why the hell I am not using getText ?, have a Guess). And compare the text and check.
Answer 4 : Write locator for the option directly and find the element and do nothing, if we can find element then result is positive otherwise negative
Doubt on 4 : How do you decide, it present only on dropdown not anywhere else on the page, because in both cases Answer 4 results positive.
Answer 5 : Write an Xpath/Css locator based on the parent(dropdown) and then find a child (the target) like, //select[@id='some']/option[text()='cherchertech'], if element found, then positive otherwise negative. We can have try and catch block here.
Answer 6 : What if try and catch block is irritating/irrelevant to test, then use the same XPath as Answer 4but use findElements instead of findElement. Now check the number of elements, if 0 then negative otherwise positive All the above answers are correct, use it based on the requirement but answer in the interview based on your experience, I would go with answers 5 and 6
How do you check whether an element enabled or not ?, condition: there is no such attribute as "disabled" in the element ?
When there is no such attribute as disabled in the element, the isEnabled() method from selenium does not work.
Solution : There is some attribute that makes the element to be disabled, so we have to find the element and get the attribute using the getAttribute() method then compare what is the value for enabled and disabled. Based on this, we can conclude whether the element is enabled or not.
Why do we write Webdriver driver = new FirefoxDriver(), why not SearchContext driver = new FirefoxDriver() ?
Don't hurry to answer like, Webdriver is an interface and FirefoxDriver is Class. This is right, but you need to understand the question first.
He is asking about SearchContext, which is a parent interface of Webdriver, so that the answer would be. Yes, we can write like that because SearchContext is the parent of all the Interfaces and classes present in selenium.
Is it possible to automate captcha?
Yes, we can automate the captcha, but there is a limitation that we can automate our own captcha but not others'
For example, a company has captcha on their website, so somebody has to check it, but at the same time, it is not possible for a manual tester to check all the captcha's.
So we have to automate the captcha in the dev/QA environment by getting the captcha answer in some attribute of the element, so based on that attribute, we can enter the value to the text bar, which accepts captcha value.
We should remove this attribute while pushing the code to the Live environment.
Testcase failed saying "ElementNotVisible", but when analyzed manually, the element is visible ? How to Handle it ?
There are a couple of things that may cause this issue.
- The element may not be visible in automation due to the speed of selenium.
- If you closed a hidden division pop up and tried to perform the action, then there is a chance that hidden division popup' animation was not over, which could cause this issue.
- There could be another element which has the same XPath or locator on some other page
Do implicit wait has any impact on findElements ?
Most of the time, the implicit wait will not work with findElements, but only when there are no elements for the given locator, then only implicit wait works from findElements.
Check If An Element Exists?
You may need to perform an action based on a specific web element being present on the web page.
You can use the below code snippet to check if an element with id 'element-id' exists on the web page.
if(driver.findElements(By.id("element-id")).size()!=0){
System.out.println("Element exists");
}else{
System.out.println("Element donot exists");
}
In test automation, we use both assert and verify commands. What is the difference between them and when are they used?
The essential part of testing is the validation of results. In test automation, throughout each test case, we make validation checks to assure that we are getting the right results.
In order to perform those checks, for example by using Selenium framework, we use the Assert* and Verify* classes of commands.
Both assert and verify command groups check if the given conditions are true. The difference is what happens if the condition is false and the check fails. When an assert command fails, the code following it will not be executed and the test will break immediately. On the other hand, when a verify command fails, the code will continue with execution regardless.
We use assert commands when the code following them depends on their success. E.g. we want to perform actions on a page only if we are logged in as an admin user. In that case, we will assert that the currently logged-in user equals the admin user, and test code will execute only if that condition is met—otherwise there’s no point, because we know we’re testing in the wrong environment.
We use verify commands when the code after them can be executed regardless of the condition having been met. E.g. checking a web page title: We just want to make sure that the page title is as expected and we will log the outcome of the verify command. An incorrect title alone shouldn’t affect the rest of what’s being tested.
How can we capture Screenshot in Selenium WebDriver?
While executing the test scripts, test cases may fail. While executing the test cases manually you can just take a screenshot and then place in a result repository. The same can be done by using Selenium WebDriver.
Some scenarios required to capture a screenshot using Selenium WebDriver are
1. Application issues
2. Assertion Failure
3. Difficulty to find Webelements on the web page
4. Timeout to find Webelements on the web page
Also selenium offers an interface referred as TakesScreenshot that has a method referred as 'getScreenShotAs' that can be used to take a screenshot of the application under test. Now in Selenium 3, there is a possibility of certain issues while capturing Screenshots. In order to overcome this situation we may use aShot utility.
In Selenium WebDriver, can you navigate back and forth in a browser?
We can use Navigate interface in order to do navigate back and forth in a browser. Following are some methods to move back, forward as well as to refresh a page.
1. driver.navigate().forward(); – It is used to navigate to the next web page with reference to the browser’s history
2. driver.navigate().back(); – It is used to take back to the previous webpage with reference to the browser’s history
3. driver.navigate().refresh(); – It is used to refresh the current web page thereby reloading all the web elements
4. driver.navigate().to(“url”); – It is used to launch a new web browser window and navigate to the specified URL
How would you differentiate driver.get() and driver.navigate.to(“url”)?
Following are the points of difference -
driver.get() is used to open an URL and it will wait till the whole page gets loaded driver.navigate.to() is used to navigate to an URL and It will not wait till the whole page gets loaded
How will you launch a browser using Selenium WebDriver?
Selenium WebDriver is an Interface where we create an Object of a required driver class like FirefoxDriver, ChromeDriver, InternetExplorerDriver etc.,
Therefore,
1. In order to launch Firefox Driver:
WebDriver driver = new FirefoxDriver();
2. In order to Chrome Driver:
WebDriver driver = new ChromeDriver();
3. In order to Internet Explorer Driver:
WebDriver driver = new InternetExplorerDriver();
4. In order to Safari Driver:
WebDriver driver = new SafariDriver();
Remember in case you use the geckodriver with Selenium, you must upgrade to Selenium 3.3.
Which verification points should be considered in Selenium?
Selenese Verify and Assert Commands are used as Verification points, in Selenium IDE. Note that in Selenium WebDriver, there is no built-in features for verification points.
It totally depends on the coding style sued. some there Verification points are -
1. Check for page title
2. Check for certain text
3. Check for certain element (text box, button, drop down, etc.)
Can you differentiate between “/” and “//”
Single Slash “/” – Single slash is primarily used to create XPath with absolute path this means the XPath would be created to start selection from the document node/start node.
Double Slash “//” – On the other hand, Double slash is used to create XPath with relative path this means the XPath would be created to start selection from anywhere within the document.
What do you know about XPath?
XPath is mainly used to locate the elements. With the help of XPath, we can navigate through elements and attributes in an XML document and thereby locate web elements like textbox, button, checkbox, Image etc., in a web page.
What is Selenium WebDriver?
Selenium WebDriver is a browser automation framework that accepts commands and sends them to a browser. Selenium WebDriver is implemented through a browser-specific driver.
Such that it controls the browser by directly communicating with it. Selenium WebDriver supports Java, C#, PHP, Python, Perl, Ruby.
How do you define Selenium RC?
Selenium RC or Selenium Remote Control was one of the main Selenium project for a long time period prior to the WebDriver merge brought up Selenium.
Can we use Python in selenium?
Yes, Selenium supports Python programming language.
Selenium has a Python driver, using which test cases for testing web applications can be made in Python programming language.
Selenium supports following Python frameworks
Unittest
Pyunit
py.test
robot framework
What is the use of xpath in Selenium?
XPath in Selenium is used to locate elements on a webpage using the HTML DOM data structure.
XPath expands to XML Path. XPath is a Selenium selector for selecting specific elements on a web page. XPath uses XML path expression for finding element on a webpage.
XPath is the most used selector in Selenium.
What is the correct syntax to instantiate a Edge browser session?
The correct syntax to instantiate a Edge browser session is WebDriver driver = new EdgeDriver();
What is default maximum number of browsers that can run in parallel on the node under Selenium Grid?
5 number of browsers
What is the use of selenium?
Selenium is an open source software which automates web browser interaction and hence, testing of web applications.
Various users can access web or mobile applications on multiple web browsers like Chrome, Firefox, Safari, Internet Explorer, etc. and on different versions of each web browser.
It is very difficult task to check the functionality, load and performance of the web application on each of the web browser and their respective versions.
Selenium
- Executes on popular web browsers and operating systems
- can be accessed by different programming languages and testing frameworks.
Selenium can be used to
- Test web applications
- Test mobile applications, running on web browsers
- Run regression tests
- Execute functional tests
- Has headless browser option
- Can also be used for web scraping
- Gives complete data capture and logging
- Provides graphical snapshot as well
- Compatible with all major programming languages
Supported programming language and testing frameworks, are
- C# - NUnit
- Haskell
- Java - JUnit, TestNG
- JavaScript - WebdriverJS, WebdriverIO, NightwatchJS, NemoJS
- Objective-C
- Perl
- PHP - Behat + Mink
- Python - unittest, pyunit, py.test, robot framework
- R
- Ruby - RSpec, Test::Unit
Supported web browsers are
- Firefox - Support for Firefox is the latest release, the previous release, the latest ESR release and the previous ESR release.
- Internet Explorer - Versions 7, 8, 9, 10 and 11 are supported. Version 11 requires additional configuration.
- Safari - SafariDriver requires Safari 5.1+
- Opera - OperaChromiumDriver can be used without extra setup on Chromium-based versions of Opera starting from version 26.
- Chrome - Version 70 onwards
Operating Systems
- Microsoft Windows - Most versions starting from Windows 7
- Apple OS X - Recent version of OS
- Linux - Ubuntu latest stable release
What are the DevOps tools?
The DevOps tools are used in the DevOps process and usually includes various categories like
- Versioning – Git
- DevOps Automation – Jenkins, Puppet, Ansible
- Test Automation – Selenium, Jmeter
- Virtualization – Docker, Kubernetes
- Build tool - Gradle
What are the conditions to automate a test?
The conditions to automate a test are -
1. Repetitive Tasks
2. Smoke and Sanity Tests
3. Test with multiple data set
4. Regression test cases
Why automation testing?
- Automation testing improves efficiency of testing.
- Reduced testing efforts and costs.
- Testing can be replicated across different platforms.
- Gives accurate results.
- Usually used for large applications with stringent deadlines.
Explain load testing on websites?
To access a website, a user sends a “request” to that website’s server, and the server sends back a response in the form of the website you want to access. quality assurance engineers and automation engineers just need to multiply the number of responses sent to simulate different traffic loads, to load test a website. The web server’s response to the influx of virtual users be measured. To determine performance issues and server capacity this is used.
When you will not automate testing?
One should not automate in following cases :
- When the Application Under Test changes frequently
- One time test cases
- Adhoc – Random testing
What are the conditions during which we cannot use automation testing for agile method?
Automation testing is not useful for agile methods in conditions like:
- When Agile testing always ask for changes in the requirements
- When there is a need of Exhaustive level of documentation in the Agile
- Only appropriate for those regression tests during agile testing like continuos integration.
Name the type of tests can be run with the selenium framework?
Selenium framework can be used for load testing, regression testing, and functional testing of web applications.
List the five essential types of test steps?
- Test object
- Functions
- Utility
- Comment
- Programming logic
Selenium Webdriver Commands
Browser Commands:
The browser commands use to open the browser, close the browser and open the website by get the url.
get :- It is to open the URL of the web application.
Syntax: driver.get(“url”);
quit():- It is to close the browser.
Syntax: driver.quit();
close:- It is to close the child or pop up window.
Syntax: driver.close();
Interactive Commands:
The interactive commands use to interact with the web application like, enter values in the textbox, clear the values from the text box, click any button, check box or radio button, select the values from the dropdown.
sendkeys:- It is to enter some value in the text box.
Syntax: driver. findelement (By.name (“username”)). sendkeys(“name1”);
clear:- It is to clear the data from the text box.
Syntax: driver. findelement (By.name (“username”)). clear();
click:- By using this command we can clink on a button, radio button, checkbox, image and link.
Syntax: driver. findelement (By.name (“button1”)). click();
newSelect:- It is to select a value from a dropdown and a list box.
Syntax: new Select(driver.findElement(By.id(“continents”))).selectByVisibleText(“Australia”);
Information Commands:
The information commands use to extract the information within the tags, outside the tags or dropdowns etc. from the applications.
getText():- It is to take the information from the application which is available outside of the tags.
getAttribute():- It is to take the information from the application which is available in between the tags.
getOptions():-It is to take the information from the application which is available within a dropdown and a list box.
String Comparison Commands:
We can compare the strings with another string by using the below commands.
equals:- It is to compare the string with another object where it is case sensitive.
equalsIgnoreCase:- It is also to compare with another string but it is not case sensitive.
Contains:- It is to check that whether the sequence of characters are available in string or not.
Validation Commands:
The validation commands use to validate the element availability, enable, disable and select the check boxes etc.
isDisplayed():- It is to check whether the element is available or not.
isEnabled():- It is to check whether the element is enabled or disabled.
isSelected():- It is to validate whether the radio button or check box is selected or not.
Different Types of Selenium Wait Commands
While executing scripts, sometimes we may face an exception “Element Not Visible Exception“. This exception appears when there is a delay in loading time of the elements which we are interacting. To overcome this issue we need to use Wait Commands.
Different Types of Selenium Wait Commands are:
- Implicit Wait
- Explicit Wait – WebDriverWait
- FluentWait
Implicit Wait:
The implicit wait tells to the WebDriver to wait for certain amount of time before it throws an exception. Once we set the time, WebDriver will wait for the element based on the time we set before it throws an exception. The default setting is 0 (zero). We need to set some wait time to make WebDriver to wait for the required time.
Note: Implicit Wait is in place for the entire time the browser is open. Time taken to search all the elements are based on the time fixed for the implicit wait.
Syntax:
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
Implicit Wait time is applied to all the elements in the script.
Implicit wait will accept 2 parameters, the first parameter will accept the time as an integer value and the second parameter will accept the time measurement in terms of SECONDS, MINUTES, MILISECOND, MICROSECONDS, NANOSECONDS, DAYS, HOURS, etc.
Explicit Wait:
Explicit waits are confined to a particular web element. Explicit Wait is code you define to wait for a certain condition to occur before proceeding further in the code.
Explicit wait is of two types:
WebDriverWait:
WebDriverWait is applied on certain element with defined expected condition and time. This wait is only applied to the specified element. This wait can also throw exception when element is not found.
The following are the Expected Conditions that can be used in Explicit Wait
- alertIsPresent()
- elementSelectionStateToBe()
- elementToBeClickable()
- elementToBeSelected()
- frameToBeAvaliableAndSwitchToIt()
- invisibilityOfTheElementLocated()
- invisibilityOfElementWithText()
- presenceOfAllElementsLocatedBy()
- presenceOfElementLocated()
- textToBePresentInElement()
- textToBePresentInElementLocated()
- textToBePresentInElementValue()
- titleIs()
- titleContains()
- visibilityOf()
- visibilityOfAllElements()
- visibilityOfAllElementsLocatedBy()
- visibilityOfElementLocated()
Syntax:
/WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
WebDriverWait wait = new WebDriverWait (driver, 20);
wait.until(ExpectedConditions.VisibilityofElementLocated(By.xpath(""//button[@value='Save Changes']"")));
FluentWait:
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.
To say in effortless manner, it tries to find the web element repeatedly at regular intervals of time until the timeout or till the object gets found.
We use Fluent Wait commands mainly when we have web elements which sometimes visible in few seconds and some times take more time than usual to visible. Mainly in Ajax applications
Syntax:
Wait wait = new FluentWait(WebDriver reference)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);
WebElement foo=wait.until(new Function<WebDriver, WebElement>() {
public WebElement applyy(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
Example:
Wait wait = new FluentWait<WebDriver>(driver)
.withTimeout(45, TimeUnit.SECONDS)
.pollingevery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
Fluent Wait uses two parameters – timeout value and polling frequency. In the above syntax we took time out value as 45 seconds and polling frequency as 5 seconds.
The maximum amount of time (45 seconds) to wait for a condition and the frequency (5 seconds) to check the success or failure of a specified condition. If the element is located with in this time frame it will perform the operations else it will throw an “ElementNotVisibleException”