Question: What is Selenium?
Answer:
Selenium is a suite of software tools to automate web browsers across many platforms (Different Operation Systems like MS Windows, Linux Macintosh etc.). It was launched in 2004, and it is open source Test Tool suite.
Question: What is Selenium WebDriver?
Answer:
Selenium WebDriver is a tool for writing automated tests of websites. It is an API name and aims to mimic the behavior of a real user, and as such interacts with the HTML of the application. Selenium WebDriver is the successor of Selenium Remote Control which has been officially deprecated.
Question: Explain Selenium Web Driver Architecture?
Answer:
Selenium Web Driver Architecture contains following components as mentioned below:
Question: What is cost of WebDriver, is this commercial or open source?
Answer:
Selenium is an open source and free of cost.
Question: How you specify browser configurations with Selenium 3.0?
Answer:
Following driver classes are used for browser configuration
AndroidDriver,
ChromeDriver,
EventFiringWebDriver,
FirefoxDriver,
HtmlUnitDriver,
InternetExplorerDriver,
IPhoneDriver,
IPhoneSimulatorDriver,
RemoteWebDriver
Question: Which web driver implementation is fastest?
Answer:
HTMLUnitDriver. Simple reason is HTMLUnitDriver does not execute tests on browser but plain http request – response which is far quick than launching a browser and executing tests. But then you may like to execute tests on a real browser than something running behind the scenes
Question: What all different element locators are available with Selenium?
Answer:
Selenium uses following method to access elements:
Question: How to capture screen shot in Webdriver ?
Answer:
Question: How do I clear content of a text box in Selenium 3.0 ?
Answer:
WebElement element= driver.findElement(By.id("ElementID"));
element.clear();
Question: How to execute java scripts function ?
Answer:
JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("pass your java scripts");
Question: How to count total number of rows of a table using Selenium 3.0 ?
Answer:
List {WebElement} rows = driver.findElements(By.className("//table[@id='tableID']/tr"));
int totalRow = rows.size();
Question. How to delete Browser Cookies with Selenium Web Driver ?
Answer:
driver.Manage().Cookies.DeleteAllCookies();
Question: How to capture page title using Selenium ?
Answer:
String title = driver.getTitle();
Question: How to store current url using Selenium?
Answer:
String currentURL = driver.getCurrentUrl();
Question: How to store page source using Selenium?
Answer:
String pagesource = driver.getPageSource();
Question: What is the difference between Assert and Verify in Selenium?
Answer:
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.
Question: What are Soft Assert and Hard Assert in Selenium?
Answer:
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
Internal Advertisement: NGA Overseas Hiring Model Live Now. Model helps connect QA Automation Engineers directly with Overseas Employers for high growth Software Testing Jobs both Remote and Onsite. To know more about the offered service, click here.
Question: What are the verification points available in Selenium?
Answer:
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 with in web page
To check for certain element (text box, button, drop down, etc.)
To check for click operation
To check for submit operation
To Check for navigation from 1 link to other link
Question: What are the different exceptions you have faced in Selenium WebDriver?
Answer:
Some of the exceptions I have faced in my current project are:
a) ElementNotVisibleException
b) StaleElementReferenceException
Element Not visible Exception:
This exception will be thrown when you are trying to locate a particular element on webpage that is not currently visible eventhough it is present in the DOM. Also sometimes, if you are trying to locate an element with the xpath which associates with two or more element.
Stale Element Reference Exception:
A stale element reference exception is thrown in one of two cases, the first being more common than the second.
The two reasons for Stale element reference are
The element has been deleted entirely.
The element is no longer attached to the DOM.
We face this stale element reference exception when the element we are interacting is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference to the element.
Some other exceptions we usually face are as follows:
c) WebDriverException
d) IllegalStateException
e) TimeoutException
f) NoAlertPresentException
g) NoSuchWindowException
h) NoSuchElementException
Question: What are the types of waits available in Selenium WebDriver?
Answer:
In Selenium we could see three types of waits such as Implicit Waits, Explicit Waits and Fluent Waits.
Question: What is Implicit Wait In Selenium WebDriver?
Answer:
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.
Question: What is WebDriver Wait In Selenium WebDriver?
Answer:
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.
Question: What is Fluent Wait In Selenium WebDriver?
Answer:
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.
Question: How to input text in the text box using Selenium WebDriver?
Answer:
By using sendKeys() method
Question: How to input text in the text box without calling the sendKeys()?
Answer:
Using Java Script Executor
Question: How to clear the text in the text box using Selenium WebDriver?
Answer:
By Using clear method
Question: How to get a text of a web element?
Answer: By using getText() method
Question: How to get an attribute value using Selenium WebDriver?
Answer:
By using getAttribute(value) method
It returns the value of the attribute passed as a parameter.
HTML:
<input name="nameSelenium" value="nextGeneration">Next Generation Automation</input>
Selenium Code:
Question: How to assert text of webpage using Selenium ?
Answer:
Selenium Code:
Internal Advertisement: NGA Overseas Hiring Model Live Now. Model helps connect QA Automation Engineers directly with Overseas Employers for high growth Software Testing Jobs both Remote and Onsite. To know more about the offered service, click here.
Question: How to click on a hyperlink using Selenium WebDriver?
Answer:
We use click() method in Selenium
Question: How to submit a form using Selenium WebDriver?
Answer:
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
Question: How to press ENTER key on text box In Selenium WebDriver?
Answer:
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);
Question:How to pause a test execution for 5 seconds at a specific point?
Answer:
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)
Question: Is Selenium Server needed to run Selenium WebDriver Scripts?
Answer:
When we are distributing our Selenium WebDriver scripts to execute using Selenium Grid, we need to use Selenium Server.
Question: What happens if I run this command. driver.get(“www.nextgenerationautomation.com”) ;
Answer:
An exception is thrown. We need to pass HTTP protocol within driver.get() method.
driver.get("https://www.nextgenerationautomation.com");
Question: What is the alternative to driver.get() method to open an URL using Selenium WebDriver?
Answer:
Alternative method to driver.get(“url”) method is driver.navigate.to(“url”)
Question: What is the difference between driver.get() and driver.navigate.to(“url”)?
Answer:
driver.get(): To open an URL and it will wait till the whole page gets loaded
driver.navigate.to(): To navigate to an URL and It will not wait till the whole page gets loaded
Question: Can I navigate back and forth in a browser in Selenium WebDriver?
Answer:
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
Question: How to fetch the current page URL in Selenium?
Answer:
To fetch the current page URL, we use getCurrentURL()
driver.getCurrentUrl();
Question: How can we maximize browser window in Selenium?
Answer:
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();
Question: What is the difference between driver.getWindowHandle() and driver.getWindowHandles() in Selenium WebDriver?
Answer:
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.
Question: What are the ways to refresh a browser using Selenium WebDriver?
Answer:
There are multiple ways to refresh a page in selenium
a) Using driver.navigate().refresh()
b) Using driver.get(“URL”) on the current URL or using driver.getCurrentUrl()
c) Using driver.navigate().to(“URL”) on the current URL d)driver.navigate().to(driver.getCurrentUrl());
e) Using sendKeys(Keys.F5) on any textbox on the webpage
Question: What is the difference between driver.close() and driver.quit() methods?
Answer:
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
Question: What is the difference between driver.findElement() and driver.findElements() commands?
Answer:
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.
Question: How to find whether an element is displayed on the web page?
Answer:
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.
a) isDisplayed()
boolean elePresent = driver.findElement(By.xpath("xpath")).isDisplayed();
b) isSelected()
boolean eleSelected= driver.findElement(By.xpath("xpath")).isSelected();
c) isEnabled()
boolean eleEnabled= driver.findElement(By.xpath("xpath")).isEnabled();
Question: How to Handle Drop Down And Multi Select List Using Selenium WebDriver?
Answer:
To handle drop down and multi select list using Selenium WebDriver, we need to use Select class.
The Select class is a Webdriver class which provides the implementation of the HTML SELECT tag. It exposes several “Select By” and “Deselect By” type methods. We use these methods to select or deselect in the drop down list or multi select object. The Select class is the part of the selenium package.
To Handle Drop Down And Multi Select List in Selenium we use the following types of Select Methods.
Types of Select Methods:
i. selectByVisibleText Method
ii. selectByIndex Method
iii. selectByValue Method
Types of DeSelect Methods:
i. deselectByVisibleText Method
ii. deselectByIndex Method
iii. deselectByValue Method
iv. deselectAll Method
Example:
WebElement mySelectElement = driver.findElement(By.name("dropdown"));
Select dropdown = new Select(mySelectElement);
dropdown.selectByVisibleText(Text);
dropdown.selectByIndex(Index);
dropdown.selectByValue(Value);
Question: How to mouse hover on a web element using WebDriver?
Answer:
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).perform();
Question: How can we handle web based pop-up?
Answer:
Alerts are basically popup boxes that take your focus away from the current browser and forces you to read the alert message. You need to do some action such as accept or dismiss the alert box to resume your task on the browser.
To handle alerts popups we need to do switch to the alert window and call Selenium WebDriver Alert API methods.
There are two types of alerts.
Windows Based
Web Based/Browser Based
To handle Browser based Alerts (Web based alert popups), we use Alert Interface. The Alert Interface provides some methods to handle the popups.
While running the WebDriver script, the driver control will be on the browser even after the alert generated which means the driver control will be behind the alert pop up. In order to switch the control to alert pop up, we use the following command :
driver.switchTo().alert();
Once we switch the control from browser to the alert window. We can use the Alert Interface methods to do required actions such as accepting the alert, dismissing the alert, get the text from the alert window, writing some text on the alert window etc.,
To get a handle to the open alert:
Alert alert = driver.switchTo().alert();
To Click on OK button:
alert.accept();
To click on Cancel button.
alert.dismiss()
To get the text which is present on the Alert.
alert.getText();
To enter the text into the alert box
alert.sendkeys(String stringToSend);
To Authenticate by passing the credentials
alert.authenticateUsing(Credentials credentials)
For Windows Based, Need to use tools like AutoIT.
Question: How to double click on element using Selenium ?
Answer:
WebElement element = driver.findElement(By.id("ElementID"));
Actions builder = new Actions(driver);
builder.doubleClick(element).build().perform();
Question: How to perform drag and drop in Selenium ?
Answer:
WebElement source = driver.findElement(By.id("Source ElementID"));
WebElement destination = driver.findElement(By.id("Taget ElementID"));
Actions builder = new Actions(driver);
builder.dragAndDrop(source, destination ).perform();
Internal Advertisement: NGA Overseas Hiring Model Live Now. Model helps connect QA Automation Engineers directly with Overseas Employers for high growth Software Testing Jobs both Remote and Onsite. To know more about the offered service, click here.
Question: How to handle hidden elements in Selenium WebDriver?
Answer:
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();");
Question: How to Find Broken Links Using Selenium WebDriver?
Answer:
One of the key test case is to find broken links on a webpage. Due to existence of broken links, your website reputation gets damaged and there will be a negative impact on your business. It’s mandatory to find and fix all the broken links before release. If a link is not working, we face a message as 404 Page Not Found.
Let’s see some of the HTTP status codes.
200 – Valid Link
404 – Link not found
400 – Bad request
401 – Unauthorized
500 – Internal Error
Consider a test case to test all the links in the home page of “NextGenerationAutomation.com”
Below code fetches all the links of a given website (i.e.,NextGenerationAutomation.com) using WebDriver commands and reads the status of each href link with the help of HttpURLConnection class.
Question: What is JavaScriptExecutor and in which cases JavaScriptExecutor will help in Selenium automation?
Answer:
In general, we click on an element using click() method in Selenium.
For example:
In general, we click on an element using click() method in Selenium.
Sometimes web controls don’t react well against selenium commands and we may face issues with the above statement (click()). To overcome such kind of situation, we use JavaScriptExecutor interface.
It provides a mechanism to execute Javascript through Selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.
There is no need to write a separate script to execute JavaScript within the browser using Selenium WebDriver script. Just we use predefined interface named ‘Java Script Executor’. We need to import the JavascriptExecutor package in the script.
Package:
import org.openqa.selenium.JavascriptExecutor;
Syntax:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);
Script – The JavaScript to execute
Arguments – The arguments to the script(Optional). May be empty.
Returns – One of Boolean, Long, String, List, WebElement, or null.
Let’s see some scenarios we could handle using this Interface:
1. To type Text in Selenium WebDriver without using sendKeys() method
2. To click a Button in Selenium WebDriver using JavaScript
3. To handle Checkbox
4. To generate Alert Pop window in selenium
5. To refresh browser window using Javascript
6. To get innertext of the entire webpage in Selenium
7. To get the Title of our webpage
8. To get the domain
9. To get the URL of a webpage
10. To perform Scroll on an application using Selenium
11. To click on a SubMenu which is only visible on mouse hover on Menu
12. To navigate to different page using Javascript
Question: How to verify PDF content using Selenium 3.0?
Answer:
NextGeneration Automation will explain the procedure to verify PDF file content using java WebDriver. As some time we need to verify content of web application PDF file, opened in browser.
Use below code in your test scripts to get PDF file content.
//get current URL PDF file URL
URL url = new URL(driver.getCurrentUrl());
//create buffer reader object
BufferedInputStream fileToParse = new BufferedInputStream(url.openStream());
PDFParserPDFParser = newPDFParser(fileToParse);
PDFParser.parse();
//savePDF text into strong variable
String pdftxt = newPDFTextStripper().getText(pdfParser.getPDDocument());
//closePDFParser object
PDFParser.getPDDocument().close();
After applying above code, you can store all PDF file content into “pdftxt” string variable.
Now you can verify string by giving input. As if you want to verify “Selenium or WebDiver” text. Use below code.
Assert.assertTrue(pdftxt.contains(“Next Generation Automation”));
Question: How to handle Ajax calls in Selenium WebDriver?
Answer:
Handling AJAX calls is one of the common issues when using Selenium WebDriver. We wouldn’t know when the AJAX call would get completed and the page has been updated. In this post, we see how to handle AJAX calls using Selenium.
AJAX stands for Asynchronous JavaScript and XML. AJAX allows the web page to retrieve small amounts of data from the server without reloading the entire page. AJAX sends HTTP requests from the client to server and then process the server’s response without reloading the entire page. To handle AJAX controls, wait commands may not work. It’s just because the actual page is not going to refresh.
When you click on a submit button, the required information may appear on the web page without refreshing the browser. Sometimes it may load in a second and sometimes it may take longer. We have no control over loading time. The best approach to handle this kind of situations in selenium is to use dynamic waits (i.e. WebDriverWait in combination with ExpectedCondition)
Some of the methods which are available are as follows:
1. titleIs() – The expected condition waits for a page with a specific title.
wait.until(ExpectedConditions.titleIs(“Deal of the Day”));
2. elementToBeClickable() – The expected condition waits for an element to be clickable i.e. it should be present/displayed/visible on the screen as well as enabled.
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath")));
3. alertIsPresent() – The expected condition waits for an alert box to appear.
wait.until(ExpectedConditions.alertIsPresent()) !=null);
4. textToBePresentInElement() – The expected condition waits for an element having a certain string pattern.
wait.until(ExpectedConditions.textToBePresentInElement(By.id(“title’”), “text to be found”));
Question: List some scenarios which we cannot automate using Selenium WebDriver?
Answer:
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
Question: What is Object Repository in Selenium WebDriver?
Answer:
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.
Question: How you build Object Repository in your project?
Answer:
In QTP, there is an Object Repository concept. When a user records a test, the objects and its properties are captured by default in an Object Repository.
QTP uses this Object Repository to play back the scripts.
Coming to Selenium, there is no default Object Repository concept. It doesn’t mean that there is no Object Repository in Selenium. Even though there is no default one still we could create our own.
In Selenium, we call objects as locators (such as ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, XPath, and CSS). Object repository is a collection of objects. One of the ways to create Object Repository is to place all the locators in a separate file (i.e., properties file).
But the best way is to use Page Object Model. In the Page Object Model Design Pattern, each web page is represented as a class. All the objects related to a particular page of a web application are stored in a class.
Question: What is Page Object Model in Selenium?
Answer:
Page Object Model is a Design Pattern which has become popular in Selenium Test Automation. It is widely used design pattern in Selenium for enhancing test maintenance and reducing code duplication.
Page object model (POM) can be used in any kind of framework such as modular, data-driven, keyword driven, hybrid framework etc. A page object is an object-oriented class that serves as an interface to a page of your Application Under Test(AUT).
The tests then use the methods of this page object class whenever they need to interact with the User Interface (UI) of that page. The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently, all changes to support that new UI is located in one place.
Question: What is Page Factory?
Answer:
We have seen that ‘Page Object Model’ is a way of representing an application in a test framework. For every ‘page’ in the application, we create a Page Object to reference the ‘page’ whereas a ‘Page Factory’ is one way of implementing the ‘Page Object Model’.
Page Object is a class that represents a web page and hold the functionality and members.
Page Factory is a way to initialize the web elements you want to interact with within the page object when you create an instance of it.
Code Snippet:
@FindBy(how=How.XPATH, using="//div[text()='Account Settings']")
WebElement profileDropdown;
@FindBy(how=How.XPATH, using="//text()[.='Log Out']/ancestor::span[1]")
WebElement logoutLink;
@FindBy(how=How.XPATH, using="///div[text()='Good afternoon, SoftwareTesting!']")
loggedInUserNameText;
FbLoginPage loginpage = PageFactory.initElements(driver, FbLoginPage.class);
Question: What are the advantages of Page Object Model Framework?
Answer:
Code reusability – We could achieve code reusability by writing the code once and use it in different tests.
Code maintainability – There is a clean separation between test code and page specific code such as locators and layout which becomes very easy to maintain code. Code changes only on Page Object Classes when a UI change occurs. It enhances test maintenance and reduces code duplication.
Object Repository – Each page will be defined as a java class. All the fields in the page will be defined in an interface as members. The class will then implement the interface.
Readability – Improves readability due to clean separation between test code and page specific code
Question: How can you use the Recovery Scenario in Selenium WebDriver?
Answer:
By using “Try Catch Block” within Selenium WebDriver Java tests.
try {
driver.get("www.SoftwareTestingMaterial.com");
}catch(Exception e){
System.out.println(e.getMessage());
}
Question: How to verify response 200 code using Selenium ?
Answer:
Next Generation Automation will explain you to verify HTTP response code 200 of web application using java webdriver. As webdriver does not support direct any function to verify page response code. But using "WebClient" of HtmlUnit API we can achieve this.
Html unit API is GUI less browser for java developer, using WebClent class we can send request to application server and verify response header status.
Below code, used in my Webdriver script to verify response 200 of web application
String url = "http://www.google.com/";
WebClient webClient = new WebClient();
HtmlPage htmlPage = webClient.getPage(url);
//Verify response
Assert.assertEquals(200,htmlPage.getWebResponse().getStatusCode());
Assert.assertEquals("OK",htmlPage.getWebResponse().getStatusMessage());
If HTTP authentication is required in web application use below code.
String url = "Application Url";
WebClient webClient = new WebClient();
DefaultCredentialsProvider credential = new DefaultCredentialsProvider();
//Set some example credentials credential.addCredentials("UserName", "Passeord"); webClient.setCredentialsProvider(credential);
HtmlPage htmlPage = webClient.getPage(url);
//Verify response
Assert.assertEquals(200,htmlPage.getWebResponse().getStatusCode());
Assert.assertEquals("OK",htmlPage.getWebResponse().getStatusMessage());
Question: Where you have applied OOPS in Automation Framework
Answer:
OOPS concepts contains following:
a) ABSTRACTION
b) INTERFACE
c) INHERITANCE
d) POLYMORPHISM
e) METHOD OVERLOADING
f) METHOD OVERRIDING
g) ENCAPSULATION
Internal Advertisement: NGA Overseas Hiring Model Live Now. Model helps connect QA Automation Engineers directly with Overseas Employers for high growth Software Testing Jobs both Remote and Onsite. To know more about the offered service, click here.
ABSTRACTION
In Page Object Model design pattern, we write locators (such as id, name, xpath etc.,) in a Page Class. We utilize these locators in tests but we can’t see these locators in the tests. Literally we hide the locators from the tests.
Abstraction is the methodology of hiding the implementation of internal details and showing the functionality to the users.
INTERFACE
Basic statement we all know in Selenium is
WebDriver driver = new FirefoxDriver();
WebDriver itself is an Interface.
So based on the above statement WebDriver driver = new FirefoxDriver();
We are initializing Firefox browser using Selenium WebDriver. It means we are creating a reference variable (driver) of the interface (WebDriver) and creating an Object.
Here WebDriver is an Interface as mentioned earlier and FirefoxDriver is a class.
An interface in Java looks similar to a class but both the interface and class are two different concepts. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract. We can achieve 100% abstraction and multiple inheritance in Java with Interface.
INHERITANCE
We create a Base Class in the Framework to initialize WebDriver interface, WebDriver waits, Property files, Excels, etc., in the Base Class.We extend the Base Class in other classes such as Tests and Utility Class.
Extending one class into other class is known as Inheritance.
POLYMORPHISM
Combination of overloading and overriding is known as Polymorphism. We will see both overloading and overriding below.
Polymorphism allows us to perform a task in multiple ways.
METHOD OVERLOADING
We use implicit wait in Selenium. Implicit wait is an example of overloading. In Implicit wait we use different time stamps such as SECONDS, MINUTES, HOURS etc.
A class having multiple methods with same name but different parameters is called Method Overloading
METHOD OVERRIDING
We use a method which was already implemented in another class by changing its parameters. To understand this you need to understand Overriding in Java.
Declaring a method in child class which is already present in the parent class is called Method Overriding. Examples are get and navigate methods of different drivers in Selenium
ENCAPSULATION
All the page classes in a framework are an example of Encapsulation. In POM classes, we declare the data members using @FindBy and initialization of data members will be done using Constructor to utilize those in methods.
Encapsulation is a mechanism of binding code and data together in a single unit.
Question: How to handle browser (chrome) notifications in Selenium?
Answer:
In Chrome, we can use ChromeOptions as shown below.
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
WebDriver player = new ChromeDriver(options);
Question: How To Highlight Element Using Selenium WebDriver
Answer:
In selenium we need to get the help of JavascriptExecutor interface to achieve this.
Let’s make the above code as a function. So whenever we want to highlight particular element, we could use this method to achieve our goal.
Question: How to achieve Database testing in Selenium?
Answer:
As we all know Selenium WebDriver is a tool to automate User Interface. We could only interact with Browser using Selenium WebDriver.
Sometimes, we may face a situation to get the data from the Database or to modify (update/delete) the data from the Database. If we plan to automate anything outside the vicinity of a browser, then we need to use other tools to achieve our task. To achieve the Database connection and work on it, we need to use JDBC API Driver.
The Java Database Connectivity (JDBC) API provides universal data access from the Java programming language. Using the JDBC API, you can access virtually any data source, from relational databases to spreadsheets and flat files. It lets the user connect and interact with the Database and fetch the data based on the queries we use in the automation script. JDBC is a SQL level API that allows us to execute SQL statements. It creates a connectivity between Java Programming Language and the database.
Using JDBC Driver we could do the following
i. Establish a Database connection
ii. Send SQL Queries to the Database
iii. Process the results
Script to get the data from the Database – Database Testing:
Script to update the data in the Database – Database Testing:
Script to delete the data in the Database – Database Testing:
Internal Advertisement: NGA Overseas Hiring Model Live Now. Model helps connect QA Automation Engineers directly with Overseas Employers for high growth Software Testing Jobs both Remote and Onsite. To know more about the offered service, click here.
Question: How To Download File Using AutoIT In Selenium WebDriver
Answer:
Download File Using AutoIT In Selenium WebDriver
Selenium can not handle file downloading because browsers use native dialogs for downloading files. Sometime we need to download file from AUT(Application Under Test). There are several ways to automate download file in Selenium but here we see download file using AutoIT in Selenium WebDriver.
AutoIt Introduction:
AutoIt Tool is an open source tool. It is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying “runtimes” required!
Now the question is how we do download file using AutoIT Tool in Selenium WebDriver.
Follow the below steps:
Step 1: Download Autoit tool from https://www.autoitscript.com/site/autoit/downloads/
and install it
Step 2: Open SciTE Script editor and add the below mentioned AutoIt script and save it as ‘DownloadFile.au3’ in your system.
AutoIt Script:
Step 3: Once the file is saved, we need to convert the ‘DownloadFile.au3’ to ‘DownloadFile.exe’. To do this we need to compile the ‘DownloadFile.au3’
Right click on the file ‘DownloadFile.au3’ and click on ‘Compile Script’ to generate an executable file ‘DownloadFile.exe’
Step 4: In Eclipse, add the below mentioned Selenium Script and run
In the above Selenium Script, we did call the AutoIt Script after clicking on the browser button which transfers windows popup box and download the required file.
Building better for tomorrow
コメント