Selenium Interview Questions and Answers
Selenium Interview Questions and Answers
Selenium Interview Questions and Answers for beginners and experts. List of frequently asked Selenium Interview Questions with answers by Besant Technologies. We hope these Selenium interview questions and answers are useful and will help you to get the best job in the networking industry. This Selenium interview questions and answers are prepared by Selenium Professionals based on MNC Companies expectation. Stay tuned we will update New Selenium Interview questions with Answers Frequently. If you want to learn Practical Selenium Training then please go through this Selenium Training in Chennai and Selenium Training in Bangalore
Best Selenium Interview Questions and Answers
Besant Technologies supports the students by providing Selenium interview questions and answers for the job placements and job purposes. Selenium is the leading important course in the present situation because more job openings and the high salary pay for this Selenium and more related jobs. We provide the Selenium online training also for all students around the world through the Gangboard medium. These are top Selenium interview questions and answers, prepared by our institute experienced trainers.
Selenium interview questions and answers for the job placements
Here is the list of most frequently asked Selenium Interview Questions and Answers in technical interviews. These questions and answers are suitable for both freshers and experienced professionals at any level. The questions are for intermediate to somewhat advanced Selenium professionals, but even if you are just a beginner or fresher you should be able to understand the answers and explanations here we give.
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”.
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.
Designing
Development
Testing
Maintenance
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.
IDE – Selenium Integrated Development Environment
RC- Selenium Remote Control
WebDriver
Selenium Grid
Selenium
QTP
Open Source
Paid
More Add-Ons we can use
Limited add-ons Only
It will support multiple browsers
It will support only Firefox, Chrome, IE
Supports different OS
It will support only Windows
It will support Mobile Devices
QTP Supports Mobile app test automation (iOS & Android) using HP solution called – HP Mobile Center
Can execute tests while the browser is minimized
Not Possible here
Can execute tests in parallel.
Can only execute in parallel but using Quality Center which is again a paid product.
List
Set
Reusability of code
Maximum coverage
Recovery scenario
Low-cost maintenance
Minimal manual intervention
Easy Reporting
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”);
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.
Test method receives data from this DataProvider. dataProvider name equals to the name of this annotation.
Syntax : @DataProvider(name = “DataProvidename”)
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
To continue the flow of execution.
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).
Types of X-path
There are two types of XPath:
1) Absolute XPath.
2) Relative XPath.
Absolute XPath:
It is the direct way to find the element.
It will start with the single forward slash(/) – which means you can select the element from the root node.
Ex : html/body/div[1]/section/div[1]/div/div/div/div[1]/div/div/div/div/div[3]/div[1]/div/h4[1]/b
Disadvantage:
If there are any changes made in the path of the element then that XPath gets failed.
Relative XPath:
It will starts from the middle of the HTML. It starts with the double forward slash (//).
It which means it can search the element anywhere on the webpage.
Ex : //*[@class=’featured-box’]//*[text()=’Testing’] How to Priority your tests in TestNG?
Ex: @Test (priority=1)
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
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
Home-directory > java org,testng.TestNG testng.xml testng2.xml testng2.xml and hit enter
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.
Rows: List<WebElement> rows=htmltable.findElements(By.tagName(“tr”));
Col: List<WebElement> columns=rows.get(rnum).findElements(By.tagName(“th”));
driver.getTtile();
driver.getCurrentUrl();
Unconditional Synchronization
– Thread.sleep();
Conditional Synchronization
– Implicit Wait
– Explicit Wait
Implicit Wait:
Selenium Web Driver has borrowed the idea of implicit waits from Watir.
The implicit wait will tell to the web driver to wait for certain amount of time before it throws a “No Such Element Exception”.
The default setting is 0. Once we set the time, web driver will wait for that time before throwing an exception.
It is for Page Level.
Syntax:
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
Explicit Wait:
This wait method for Element level.
The explicit wait is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or the maximum time exceeded before throwing an “ElementNotVisibleException” exception.
The explicit wait is an intelligent kind of wait, but it can be applied only for specified elements.
Explicit wait gives better options than that of an implicit wait as it will wait for dynamically loaded Ajax elements.
Syntax:
WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
Fluent Wait uses two parameters – timeout value and polling frequency.
First of all, it sets the following values.
1- The maximum amount of time to wait for a condition, and
2- The frequency to check the success or failure of a specified condition.
Also, if you want to configure the wait to ignore exceptions such as <NoSuchElementException>
Syntax :
Wait wait = new FluentWait(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id(“foo”));
}
});
Step By Step Analysis Of The Above Sample Code.
Step-1: Fluent Wait starts with capturing the start time to determine delay.
Step-2: Fluent Wait then checks the condition defined in the until() method.
Step-3: If the condition fails, Fluent Wait makes the application to wait as per the value set by the <pollingEvery(5, SECONDS)> method call. Here in this example, it’s 5 seconds.
Step-4: After the wait defined in Step 3 expires, start time is checked against the current time. If the difference of the wait start time (set in step-1) and the current time is less than the time set in <withTimeout(30, SECONDS)> method, then Step-2 will need to repeat.
The above steps will recur until either the timeout expires or the condition becomes true.
to switchto a frame:
driver.switchTo.frame(“Frame_ID”);
to switch to the default again.(parent)
driver.switchTo().defaultContent();
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
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.
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”);
driver.getWindowHandle(); – Single Window
driver.getWindowHandles(); – Multiple windows
Ant
Maven
Ant doesn’t has formal conventions, so we need to provide information of the project structure in build.xml file.
Maven has a convention to place source code, compiled code etc. So we don’t need to provide information about the project structure in pom.xml file.
Ant is procedural. You need to provide information about what to do and when to do through code. You need to provide order.
Maven is declarative, everything you define in the pom.xml file.
There is no life cycle in Ant.
There is life cycle in Maven.
It is a tool box.
It is a framework.
It is mainly a build tool.
It is mainly a project management tool.
The ant scripts are not reusable.
The maven plugins are reusable.
It is less preferred than Maven.
It is more preferred than Ant.
3.11
Using with SendKeys
RobotClass
AutoIT
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.
TestNG – Emailable Report or XSLT Report.
Git Repository or SVN
Read Excel Data : FileInputStream.
Write Excel data : FileOutStream
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
Example:
<?xml version=”1.0″ encoding=”UTF-8″?>
<suite name=”example suite 1″ verbose=”1″ >
<test name=”Regression suite 1″ >
<classes>
<class name=”com.first.example.demoOne”/>
<class name=”com.first.example.demoTwo”/>
<class name=”com.second.example.demoThree”/>
</classes>
</test>
</suite>
We need to specify the class names along with packages in between the classes’ tags.
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.
WebDriver is interface
FirefoxDriver is Class
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();
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();
Actions act = new Actions(driver);
action.moveToElement(element).build().perform()
Actions act = new Actions(driver);
action.doubleClick(element).build().perform();
Actions act = new Actions(driver);
action.contextClick(element).build().perform();
JExcel
Apache POI
It doesn’t support Excel 2007 and Xlsx format. It supports only Excel 2003 and .Xls format
It supports both
JXL doesn’t support Conditional formatting
It supports
JXL API was last updated in 2009
Apache POI is actively maintained
It doesn’t support rich text formatting
Apache POI supports it
It has very less documents and examples as compare to Apache POI
It has extensive set of documents and examples
Id
Name
CSSSelector
Xpath
Tagname
ClassName
LinkText
Partial LinkText
CSS Selector
List<WebElement> allLinks = driver.findElements(By.tagName(“a”));
<suite name=”Parallel test suite” parallel=”tests”>
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
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//The below method will save the screen shot in d drive with name “screenshot.pn” open=”no” style=”default” icon=”plus” anchor=”” class=””]g”
FileUtils.copyFile(scrFile, new File(“D:\\screenshot.png”));
List<WebElement> ele = driver.findElements(By.tagName(“frame”));
System.out.println(“Number of frames in a page :” + ele.size());
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
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.
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”));
Asserts are used to perform validations in the test scripts.
There are two types of Assert:
Hard Assert
Soft Assert
When an assert fails the test script stops execution unless handled in some form. We call general assert as Hard Assert.
Hard Assert – Hard Assert throws an AssertExceptionimmediately when an assert statement fails and test suite continues with next @Test.
The disadvantage of Hard Assert – It marks method as fail if assert condition gets failed and the remaining statements inside the method will be aborted.
To overcome this we need to use Soft Assert. Let’s see what is Soft Assert.
Soft Assert – Soft Assert collects errors during @Test. Soft Assert does not throw an exception when an assert fails and would continue with the next step after the assert statement.
If there is any exception and you want to throw it then you need to use assertAll() method as a last statement in the @Test and test suite again continue with next @Test as it is.
We need to create an object to use Soft Assert which is not needed in Hard Assert.
D:\>Java –jar Jenkins.war
Jenkins 2.114
Page Object Model Framework has now a days become very popular test automation framework in the industry and many companies are using it because of its easy test maintenance and reduces the duplication of code.
The main advantage of Page Object Model is that if the UI changes for any page, it don’t require us to change any tests, we just need to change only the code within the page objects(Only at one place).
The Page Object model provides the following advantages.
There is clean separation between test code and page specific code such as locators (or their use if you’re using a UI map) and layout.
There is single repository for the services or operations offered by the page rather than having these services scattered throughout the tests.
The default port used by the hub is 4444
Advantages:
Selenium is pure open source, freeware and portable tool.
Selenium supports variety of languages that include Java, Perl, Python, C#, Ruby, Groovy, Java Script, and VB Script. etc.
Selenium supports many operating systems like Windows, Macintosh, Linux, Unix etc.
Selenium supports many browsers like Internet explorer, Chrome, Firefox, Opera, Safari
Selenium can be integrated with ANT or Maven kind of framework for source code compilation.
Selenium can be integrated with TestNG testing framework for testing our applications and generating reports.
Selenium can be integrated with Jenkins or Hudson for continuous integration.
Selenium can be integrated with other open source tools for supporting other features.
Selenium can be used for Android, IPhone, Blackberry etc. based application testing.
Selenium supports very less CPU and RAM consumption for script execution.
Selenium comes with different component to provide support to its parent which is Selenium IDE, Selenium Grid and Selenium Remote Control (RC).
Disadvantages:
Selenium needs very much expertise resources. The resource should also be very well versed in framework architecture.
Selenium only supports web based application and does not support windows based application.
It is difficult to test Image based application.
Selenium need outside support for report generation activity like dependence on TestNG or Jenkins.
Selenium does not support built in add-ins support.
Selenium user lacks online support for the problems they face.
Selenium does not provide any built in IDE for script generation and it need other IDE like Eclipse for writing scripts.
Selenium Automation Engineers are bit in scarcity these days.
Selenium script creation time is bit high.
Selenium does not support file upload facility.
Selenium partially supports for Dialog boxes.
Selenium 3.0
Using with Select Class
Syntax:
Select sel = new Select(driver.findElement(By.id(“test”));
Sel.SelectByVisibleText(“value”);
Sel.SelectByValue(“2”);
Sel.SelectByIndex(4);
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.
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:
Selenium is a Suite (group) of tools i.e., Selenium IDE, Selenium WebDriver and Selenium Grid to automate web browsers across many platforms.
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.
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.
The following syntax can be used to launch Browser:
WebDriver driver = new FirefoxDriver();
WebDriver driver = new ChromeDriver();
WebDriver driver = new InternetExplorerDriver();
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”);
}
}
By using getCssvalue()
For example:
driver.findElement(By.id(“text”)).getCssValue(“color”);
By using getSize()
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_’)]”));
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
Test(enabled=false) annotation is used to skip a test case in TestNG
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
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();
To handle drop down, an object to be created to the Select class.
Select dropDown= new Select(element);
The value in the dropdown can be selected using 3 ways:
Syntax:
selectByValue()
selectByVisibleText()
selectByIndex()
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.
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.
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”;
}
}
//Pass Username and Password in URL itself
driver.get(“http://username:password@www.xyz.com”);
driver.findElement(By.id(“email”)).sendKeys(Keys.ENTER);
//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”);
Usually, the time delay between two webdriver elements is 0 milliseconds but the application speed varies based on different factors:
Internet speed
Server response time
System configuration
To avoid the timing errors(Synchronization errors) between the tool (webdriver) and application, we take the help of Synchronization commands.
Implicit Wait: It is used to define wait for all the elements of WebDriver.
Syntax:
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Explicit Wait: It is used to define wait for specific element of WebDriver.
Syntax:
WebDriverWait wait=new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.linkText(“Gmail”)));
JavascriptExecutor jsx=((JavascriptExecutor) driver);
jsx.executeScript(“window.scrollBy(0,500)”,””);
String text=”Selenium”;
boolean isTextPresent=(driver.getPageSource()).contains(text);
System.out.println(text+” is present in the web page”);
The different exceptions in Selenium web drivers are
WebDriverException
ElementNotVisibleException
NoAlertPresentException
NoSuchWindowException
NoSuchElementException
TimeoutException
StaleElementReferenceException
By using moveToElement() method in Actions class
//Create an object to Actions class
Actions action = new Actions(driver);
action.moveToElement(element);
driver.switchTo().frames(id/name/index/loactor);
To switch back from child frame to parent frame use method parentFrame()
Syntax:
driver.switchTo().parentFrame();
To switch back from a frame use method defaultContent()
Syntax:
driver.switchTo().defaultContent();
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’]
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.
SearchContext is the super interface of WebDriver
We can load a webpage(url) in two ways:
get(“URL”);
navigatr().to(“URL”);
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();
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();”);
Bitmap comparison Is not possible using Selenium WebDriver
Automating Captcha is not possible using Selenium WebDriver
We can not read barcode using Selenium WebDriver
We can not automate OTP
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.
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
The default port used by the hub is 4444
driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getWidth();
driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getHeight();
WebElement is an Interface.
The default port used by the Node is 5555
Driver refers to the Web browser. Selenium can handle web-based testing using any browser hence termed as Selenium WebDriver. A browser can have only one driver instance.
In the web browser, Each of the elements are identified using HTML tags. Inorder to traverse through this HTML tag XPath is mainly used.
Absolute XPath – where we traverse from the root tag to our element needed
Relative XPath – exactly we go to the specified element.
Relative path should be preferred as – no need to update the elements of any changes has occurred in the future. If absolute XPath is used if changes in the elements occurred each & every time the element should be updated.
AutoIt uses keyboard event to navigate and download the file in the specified location
What are the different Framework model preferred?
Specflow widely preferred model based on BDD framework which contain Feature file and the related step definition file.
While working with IE, sometimes IE browser popups a window with a message “Do you want to Stay in this Page Or Leave this page?”. This can’t be handled through Selenium.
Solution : by default, Leave this page button will be active just press Enter using keyboard event to continue…
Framework is the model that show how you’re project works in backend.
Framework makes code clean and reasuable.
Framework can be independent based on the testers creativity.
Framework makes code easily understandable and organised.
It can be created as a constant on either of external files such as JSON,XML, Excel files.
In Files, a concept called FileWatcher is available which keeps on watches whether the file is download in the particular location or not.
Thread sleep makes the browser to be idle for sometime without performing any tasks. This waste the time is not preferred. Because Sometimes when waiting for longer time the browser can lose its scope and become inactive Hence WebDriver waits are preferred instead.
MSTest is supported in C# language which is available by default in the visual Studio used a unit testing tool. Where nunit is also a testing tool which should be downloaded and configured with the Selenium & Visual studio.
Screenshot should be taken in the catch block for failed testcases.
All the related relevant information regarding each of the testcases must be captured and an html report should be prepared. Various external tools are available to create reporting such as Extent report, ant, maven….
It is mandatory to call assertAll() method at the end of your test when comparing expected and actual result.
If you do not use assertAll(),the test will be passed even if any assert objects throws exceptions
See the below example.
public class SoftAsserts {
@Test public void userName() { SoftAssert s=new SoftAssert(); String eResult=”Sudeer kumar”; String aResult=”Sudeer Raj”; s.assertEquals(aResult, eResult); //s.assertAll();
} } |
If comparison fails, it will not execute the statements written after “assertAll()” method.
See the below example.
public class Example {
@Test public void comparison() { SoftAssert s=new SoftAssert(); String expected=”King”; String actual=”Queen”; s.assertEquals(actual, expected); s.assertAll(); //The comparison will fail so it will not execute the below statement System.out.println(“This statement won’t be executed”);
} } |
By providing different name to the excel file in the path of the file which is used as an argument for the FileOutputStream constructor.
See the below example.
public class S27_WriteDataIntoExcel
{
public static void main(String[] args) throws EncryptedDocumentException, IOException { FileInputStream fis=new FileInputStream(“D://FileOne.xlsx”); Workbook wb = WorkbookFactory.create(fis); Sheet sheet = wb.getSheet(“sheet1”); //Write data into new row and new cell sheet.createRow(1).createCell(0).setCellValue(“New Value”); //Writing data into excel FileOutputStream fos=new FileOutputStream(“D://FileTwo.xlsx”); //In the above line, change the name of the file if you want to “Save As” wb.write(fos);
}
} |
By providing different name to the excel file in the path of the file which is used as an argument for the FileOutputStream constructor.
See the below example.
public class S27_WriteDataIntoExcel
{
public static void main(String[] args) throws EncryptedDocumentException, IOException { FileInputStream fis=new FileInputStream(“D://FileOne.xlsx”); Workbook wb = WorkbookFactory.create(fis); Sheet sheet = wb.getSheet(“sheet1”); //Write data into new row and new cell sheet.createRow(1).createCell(0).setCellValue(“New Value”); //Writing data into excel FileOutputStream fos=new FileOutputStream(“D://FileTwo.xlsx”); //In the above line, change the name of the file if you want to “Save As” wb.write(fos);}} |
using contains () function
E.g.: //a[contains(text(),’inbox’]
cssSelector | xpath |
Faster | Slow |
Browser Independent | Browser dependent
|
Do not support text | Support text |
Do not support Group index | Support Group index |
/.. Not supported | /.. Support
|
ancestor Not Support | Ancestor Support |
Using switchTO().activeElement();
To click on a button we can use following methods.
- Using JavaScript Executor.
- submit(); Method of WebElement.
- sendKeys(Keys. Enter) Method of WebElement
- Click(); of WebElement.
- Robot class.
Note : Submit method can be used only if type of the button is submit or else we get NoSuchElementException.
- If the element is inside the frame, then we should switch to the frame before finding the element.
- In order to switch to the frame, we use following statement
driver. SwitchTo().frame(arg);
In the above statement frame method is overloaded. It takes an argument of type
- int : Index which starts from 0.
- String : id or name of the frame.
- WebElement : Address of the frame.
driver. SwitchTo().frame(int);
driver. SwitchTo().frame(String);
driver. SwitchTo().frame(WebElement);
Answer:To Handle drop down menu, we use moveToElement method of Actions Class.
- Right clicking is also called Context click.
- If we right click anywhere on the page we see list of option which is called as Context Menu.
- To right click we use contextClick() method of Actions Class.
- We cannot inspect the context menu hence we select the option present in context menu by pressing the shortcuts such as T for new tab W for New Window etc.
Actions class is present in interactions package.
we must call ‘perform()’ method.
- Handling Context Menu
- Handling Dropdown Menu
- Drag and Drop
- Composite action
- Double click..Etc
No
To handle the JavaScript Pop-up, we use switchTo().alert() statement which will transfer the control to alert Pop-up or Confirm Pop-up. Then we use getText() method to get the message present on the pop-up. We can use accept method to click ok and we use dismiss method to click cancel.
Hidden division pop-up is displayed when the “display” property is set to “block”
Calendar pop-up is an example for hidden division pop-up.
we convert relative path into absolute path using getAbsolutePath() method of file class and we use converted absolute path as argument for sendKeys() method.
If the element is disabled and if we try to use SendKeys,Clear,Click methods on such element we get invalidElementStateException.
It is the unique alphanumeric string of the browser which is generated by OS for every browser window.
To get the window handle of the browser we use the getWindowHandle method.
Example : driver.getWindowHandle();
getWindowHandle returns window handle of current browser(string) whereas getWindowHandles returns window handle of all the browsers(Set<string>)
By using close() method inside For Each loop of window handles. See the below program.
public class ChildBrowserPopup
{ public static void main(String[] args) { System.setProperty(“webdriver.chrome.driver”,”./Drivers/chromedriver.exe”); //Open the browser WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get(“https://www.naukri.com/”);
//get the WindowHandles of all child browsers and close Set<String> allWindows = driver.getWindowHandles(); for(String wh:allWindows) { driver.switchTo().window(wh).close(); } } } |
org.openqa.selenium.support.ui.select.
By using isMultiple() method.
If you apply any deselect methods of select class to single select list box, we get
“UnsupportedOperationException”.
By using getOptions() method.
It means address of the element is old.
After finding the element before performing any action on that element if the page is refreshed, we get StaleElementReferenceException.
To handle StaleElementReferenceException.
- To maintain element repository.
- To encapsulate the element.
- To write the script in organized way.
We get NullPointerException.
PageFactory.initElements(WebDriver,POMClassObj);
E.g.:
- Inside POM class
PageFactory.initElements(driver,this);
- Inside Test class
PageFactory.initElements(driver, POMRefVar);
@FindBy Annotation will not allow us to use variable in place of locator value.
Locator value should be constant(final variable or hardcoded value).
It depends on number of Rows of DataProvider array.
Runtime.getRuntime().exec(“E:// AutoItCode.exe”);
Depends on number of columns of DataProvider array.
By Changing data type of two dimensional array to object.
passed
We re-run only failed test-cases using testng-failed.xml which is present inside test-out folder.
NullPointerException
Using “getCellType()” method. If it has string, it returns “1” . If it has numeric value, it returns “0”.
To execute TestNG.xml from POM.XML we should use a plugin and the name of the Plugin is “surefire”
<plugin>
<groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> <configuration> <suiteXmlFiles> <suiteXmlFile>testng.xml</suiteXmlFile> </suiteXmlFiles> </configuration> </plugin>
|
Sl.# | Java Project | Maven Project |
1 | We should update jar files manually | Jar files will be updated automatically |
2 | we copy paste the jar files inside jar folder | It will be downloaded under .m2/repository folder |
3 | The Associated Jar files will be listed under Referenced libraries | Associated Jar files listed under maven dependencies |
4 | We execute the framework using testNG.xml | Here we execute the framework using pom.xml |
5 | After the execution result is stored under test-output folder | After Execution result is stored under target folder. |
Characteristics:
- We can inspect this pop-up.
- We cannot move this pop-up.
- Pop-up will be in different colors.
- It may or may not have buttons.
Solution:
- We can handle this pop-up using ‘findElement()’ method itself. (Example for Hidden Division pop-up is ‘Calendar’)
public class Swapping {
public static void main(String[] args){ int n1=10; int n2=20; System.out.println(“Before Swapping: ” +”n1=”+n1+” “+”n2=”+n2); n1=n1*n2; n2=n1/n2; n1=n1/n2; System.out.println(“After Swapping: ” +”n1=”+n1+” “+”n2=”+n2); } } |
- Supports execution of regression test cases
- Enables parallel execution
- Improves accuracy thereby reducing human-generated errors
- Saves time and money
- Regression
- Functional
X path is used to find an element of on the webpage.
The types are
- Relative X path
- Absolute X path
The tools are
- Chro Path
- Xpath Finder
- Fire Path
Browsers: Google chrome, IE, Mozilla Firefox, Safari, Opera etc.
Send keys, Click, Clear, Submit are the basic web element inputs.
WebDriver driver = new FirefoxDriver();
WebDriver driver = new ChromeDriver();[/togle_content]
- Functional
- Regression
- Sanity
- Smoke
- Responsive
- Integration
- Contains
- Sibling
- Ancestor
- Selenium RC
- Selenium IDE
- Selenium Grid
- Selenium Web driver
- Open source
- Free of cost
- Language support
- Environment support
The exceptions areTimeout exception
- NoSuchElementException
- ElementNotVisibleEception
JavaScriptExecutor is commonly used as an interface to execute JavaScript through selenium web driver.
- Excel
- XML
- Text
- csv
Jason Huggins and his team developed the tool in 2004 when they were working in Thought work.
- Thread.sleep()
- SetSpeed ()
Find Element finds the first element within the current page. It returns only one value.
FindElements finds all the elements within the current page. It returns multiple values.
It is not a performance tool like load runner.
System.exit(0);
It will help the web driver to terminate the entire java program.
The basic commands are
- navigate().to()
- navigate().refresh()
The basic commands are
- close()
- quit()
Yes, it is possible. It is handled by using Advanced User Interactions API.
- QTP
- Selenium
- Rational Robot
- Coded UI
- Auto It
- Load runner
- Jmeter
- Neoload
- Selenium v1.0
- Selenium v 2.0
- Selenium v3
It is a set of commands that run your tests in selenium.
Maven, Jenkins & Docker
Assertion is state of application on which is expected.
- Implicit wait
- Explicit wait
The annotations are Test, Before, After, Ignore, before class, after class, Run with
- Android driver
- I phone driver
- OperaMobileDriver
- Eclipse
- JDK3
- Selenium Libraries
OS: Microsoft Windows, Linux, Apple OS X
Languages: Java, C#, Python, PHP, Objective -C, Perl
It depends upon the complexity and length of the test cases.2 or 3 test cases is possible.
Firefox
- Junit
- TestNG
Yes, it is possible to delete cookies.
Driver.manage().deleteAllCookies
Driver.close() is used to close current web driver instance
Driver. Quit() is used to close all opened web driver instances.
- Code re-usability.
- Code main ability
- Readability
JavaScript scrollBy() helps to scroll the document up and down.
There are two types of waits in Selenium:
- Implicit Waits
- Explicit Waits.
The major components of Selenium are:
- Selenium Webdriver
- Selenium GRID
- Selenium RC
- Selenium IDE.
Yes, Selenium supports parallel execution by using Selenium GRID.
Google Chrome, Firefox, IE, Opera, Safari etc. are some browser that supports Selenium.
Advantages of Selenium:
- The Selenium is free open-source and portable tool. There is no licensing cost involved for Selenium.
- The Selenium also supports various languages which includes Java, Python, Ruby, JavaScript etc.
- It is also compatible with various operating systems like Windows, Mac, Unix, Linux etc.
- It can also be used across number of browsers which included internet explorer, Firefox, Google Chrome etc.
Disadvantages of Selenium:
- The Selenium only supports web based applications. It doesn’t support desktop application.
- It doesn’t have any tools in Selenium’s tool suite for test management.
- There is very limited scope for image testing.
- The new features introduced by Selenium doesn’t work properly.
- There is lack of reliable technical support from anybody because Selenium is open-source tool.
No, it is impossible to automate captcha image in selenium.
There are two different methods for sending values to the textbox.
Sendkeys()
Actions.sendkeys()
To handle pop up dialog in Selenium you can use Alert class.
This can be handled by using mouse over actions class.
executable_path = path of the gecko driver
Driver = webdriver.Firefox(executable_path).
Selenium doesn’t supports mobile automation but you can still do it with Appium open-source test automation framework.
The Selendroid is the test automation framework for the different types of mobile applications. This framework drives off the user interface of Android native and hybrid applications and other mobile web applications.
By using findelemets() methods we can get number of elements for the xpath.
The major difference is that Findelement() returns one value and findelements() returns numbers of elements as the list.
You can get alert by driver.text.
You can call driver.getTitle() or driver.getPageSoruce() for reading the title of the page in Selenium.
These are the basic commands used for navigation in Selenium.
- title
- refresh()
- forward()
- back()
- page_source
- current_url
- maximize_window().
Both driver.get() and driver.navigate.to() can be used for making driver.navigate faster.
Selenium is one of the popular automation testing tool. This tool is used by so many companies to their product. Introduction to Selenium; Selenium is the open-source software-testing framework specially designed for the web applications. The testing performed on Selenium tool is known as Selenium testing. There is no need to learn a test scripting language (Selenium IDE) because Selenium offers record and playback tool for authoring testing.
Using window handlers and switch-to-method is the best way to handle multiple tabs.
System.setProperty () is used to set the path of driver executables. We can write this statement anywhere but it should be before opening the browser.
IllegalStateException
Converting sub-class object to super type is called as up-casting. We do up-casting to achieve the ‘Run time Polymorphism’. In selenium we do up-casting to execute the same method or script on many browsers.
It’s Standard in Selenium. In selenium after opening the browser we will enter the ‘URL’ using ‘get ()’ method of WebDriver interface & then we perform other cations. If we up-cast the browser object to any other interface ‘get ()’ method will be hidden & we cannot perform any other actions.
Using ‘switchTo().activeElement()’ statement.
Using ‘Dimension’ & ‘Point’ class.
WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); Dimension d=new Dimension(300, 400); driver.manage().window().setSize(d); Point p=new Point(300, 50); driver.manage().window().setPosition(p);
- Css-Selector is faster than X-path
- CSS-Selector is independent on the browser whereas X-path is dependent on the browser.
- CSS-Selector do not support ‘text()’ & ‘group Index’ whereas X-path support both.
- Navigating from one element to another element is called as x-path traversing.
- In order to traverse the html tree we use x-path axes.
- Following are the very important x-path axes.
- Child
- Descendant
- Parent
- Ancestor
- Following-sibling
- Preceding-sibling
- Out of all these, only first 3 has shortcuts.
- Child is represented by à /
- Descendant is represented by à //
- Parent is represented by à /..
Syntax:- /axes :: tag
Note: After ‘tag’ we can use index, attribute, text(), contains or another axis.
Sample html:
<html> <body> <table border='1'> <tbody> <tr> <td>Sl.No</td> <td>Subject</td> <td>Cost</td> </tr> <tr> <td>1</td> <td>Java</td> <td>7000</td> </tr> </tbody> </table> </body> </html>
Webpage:
Sl.No | Subject | Cost |
---|---|---|
1 | Java | 7000 |
Child à /child::html/child::body or html/body
Descendant à /descendant::a or //a
Ancestor à //tbody/../../.. (Navigating to html) or //tbody/ancestor::html
Xpath | Matching Elements |
---|---|
//td[text()=Sl.No]/following-sibling :: td | Subject, Cost |
//td[text()=Sl.No]/following-sibling :: td[1] | Subject |
//td[text()=Sl.No]/following-sibling :: td[2] | Cost |
//td[text()=Cost]/preceding-sibling :: td | Subject, Sl.No |
//td[text()=Cost]/preceding-sibling :: td[1] | Subject |
//td[text()=Cost]/preceding-sibling :: td[2] | Sl.No |
By using ‘getCssValue()’ method. This method is present in ‘WebElement’ interface. ‘getCssValu()’ method returns ‘String’ result. We have pass “color” argument to this method.
WebElement text=driver.findElement(By.id("headerContainer")); String textColor=text.getCssValue("color"); System.out.println(textColor); String v=Color.fromString(textColor).asHex(); System.out.println(v); if(v.equals("#000000")) { System.out.println("Color is Black"); } else { System.out.println("Color is not black"); }
By using ‘getLocation()’ method. To find x-value we use ‘getX()’ & for y-value ‘getY()’.This method is present in ‘WebElement’ interface & method returns ‘int’ result.
int x=userName.getLocation().getX(); int y=userName.getLocation().getY();
Using JavascriptExecutor
WebDriver driver=new ChromeDriver(); driver.get("http://localhost:8080/login.do"); //Entering value to Textbox String script1="document.getElementById('username').value='Vijay'"; JavascriptExecutor j=(JavascriptExecutor)driver; j.executeScript(script1); //Removing value from Textbox String script2="document.getElementById('username').value=''"; j.executeScript(script2);
Using JavascriptExecutor we can
- Scroll the page
- We can enter the value to a textbox. (sendKeys)
- We can use to remove the value present in the textbox. (clear)
- We can click on element.
- We can use to perform the action even if the element is disabled.
Implicit Wait | Explicit Wait |
---|---|
1. We do not specify the waiting condition. | 1. We have to specify the waiting condition like WebDriverWait.until() |
2. We can handle synchronization of only findElement & findElements statements. All at a time. | 2. We can handle synchronization of any statement but only one at a time. |
3. TimeUnit can be in days, hours, minutes, seconds, milliseconds, microseconds or nanoseconds. | 3. TimeUnit can be only in seconds. |
4. After the specified duration we get NoSuchElement exception. | 4. After the specified duration we get TimeOut exception. |
We can use Custom Wait (Writing our own code)
String key="webdriver.chrome.driver"; String value="./Drivers/chromedriver.exe"; System.setProperty(key, value); WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("http://localhost:8080/login.do");// use any application’s url driver.findElement(By.id("username")).sendKeys("admin"); driver.findElement(By.name("pwd")).sendKeys("manager"); driver.findElement(By.xpath("//div[.='Login ']")).click(); while(true) { try { driver.findElement(By.xpath("//a[.='Logout']")).click(); break; } catch (Exception e) { } } driver.close();
By using ‘pageLoadTimeout()’ String key="webdriver.chrome.driver"; String value="./Drivers/chromedriver.exe"; System.setProperty(key, value); WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS); try { driver.get("http://localhost:8080/login.do"); System.out.println("Page Loaded in 3-Seconds"); } catch (Exception e) { System.out.println("Page is Not Loaded in 3-Seconds"); } driver.close();
- Implicit Wait
- Explicit Wait (WebDriver Wait)
- Custom Wait
- Sleep()
- pageLoadTimeout()
Performing multiple actions at a same time such as pressing multiple keys at a same time(Ctrl+c) or performing multiple actions in mouse such as ‘Click & Scroll’, ‘Click-hold-drag’ or performing one action from keyboard & another action from mouse (Ctrl+Click) all these are called as Composite actions.
This can be done using ‘Actions’ class.
//Code for Control+Click WebElement link=driver.findElement(By.id("licenseLink")); Actions action=new Actions(driver); action.sendKeys(Keys.CONTROL).click(link).perform();
driver.get("https://www.naukri.com/"); Set<String> allWindows = driver.getWindowHandles(); for(String wh:allWindows) { driver.switchTo().window(wh).close(); }
System.out.println("Enter the required Option"); Scanner sc=new Scanner(System.in); String input = sc.nextLine(); sc.close(); if(map.containsKey(input)) { System.out.println("Option "+input+ " is present in ListBox"); if(map.get(input)>1) { System.out.println("Option is duplicate in ListBox"); } else { System.out.println("Option is not duplicate"); } } else { System.out.println("Option is not present in ListBox"); }
‘StaleElementReference’ exception means address (reference) of the element is old (stale). We get this exception
- After finding element
- If page is refreshed
Then if we try to perform the action on that element
We get ‘NullPointer’ exception.
By using ‘invocationCount’ public class Demo2 { final int i=3; @Test(invocationCount=i) public void userName() { Reporter.log("My Name is Sudeer Raj”, true); } }
Output:
My name is Sudeer Raj
My name is Sudeer Raj
My name is Sudeer Raj
Inheritance concept is one where the child class extends the parent class and inherits the methods and parameters of the Parent class.
I have implemented in my project by creating a Base class and extending to all the other class so they can make use of the driver instance
@BeforeTest
@AfterTest
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod
@BeforeSuite
@AfterSuite
@BeforeGroups
@AfterGroups
@Test
Automation testing is a technique to check the software under test and compare the real outcome with the expected result using an automation tool. It automates the execution of repetitive tasks and writes test scripts without requiring the involvement of humans while executing test cases.
The key benefits of using Automation Testing to test the software applications are such as:
- Automates the manual process to test the software application
- Executes the repetitive test cases without requiring human intervention
- Allows user to run test cases on various machines simultaneously
- Allows to perform functions as well as performance testing on the software
- Increases testing efficiency and value of software application
- Saves a lot of time because it tests application using automation tool
- Reduces testing cost and improve accuracy
- Reusability of tests and decrease testing efforts
The main reasons Selenium must be chosen as a testing tool include:
- It is open-source software and free to download and use
- Provides large scope to test the application and find errors at an early stage
- Compatible to run on various operating systems such as Linux, Windows and Mac operating systems
- Compatible with multiple browsers (IE(Internet Explorer), Google Chrome, Safari, Opera Mini, etc.)
- Supports to write test scripts in multiple languages (.Net, Python,JavaScript, Perl, Java, Ruby, etc.)
- Provides the circulated environment to perform testing and implement test easily
The list of popularly used automation testing tools to perform functional automation include:
- An open-source Selenium
- Coded User Interface
- IBM Rational Robot
- An open-source AutoIt software testing tool
- HP Quick Test Professional
Some of the popularly used automation testing tools in non-functional automation include:
- Apache JMeter
- LoadRunner software testing tool developed by HP
- Neoload
- Loadtracer
- PortSwigger BurpSuite
- Acunetrix and Webserver Stress Tool
Selenium is an automation software testing suite package which provides a set of components to support automation across various platforms, browsers, and programming languages. It includes key elements such as:
- Selenium WebDriver
- Selenium RC (Remote Control)
- Selenium IDE and Grid
Selenium IDE is a Firefox Plugin works based on principle record and playback that helps to record test cases and repeat to test application. It supports the tester to upload test scripts in multiple programming languages. But, it does provide portability and robustness of test scripts.
Selenium RC is considered as a test tool enables the user to write automated User Interface (UI) tests selecting any language comfortable to them against the website. It helps to execute test cases in various browsers.
Selenium WebDriver is a test tool that allows the tester to communicate with the web browser directly on which test scripts are executing. It uses native methods of web browser’s to automate web applications testing.
Selenium Grid is a test tool allows a tester to run selenium tests across different machines in a parallel way.
- Selenium supports multiple programming languages such as include JavaScript, RSpec, C#, Ruby, Java, Groovy, PHP and Perl
- The operating systems supported by Selenium include Mac OS, Android, Windows, Solaris, and iOS
- Selenium provides compatibility with various browsers such as IE (Internet Explorer), Firefox, Safari, Chrome, and Opera
Selenium supports various types of testing’s to test application such as
- Interface Testing
- Smoke Testing
- Unit Testing
- Regression Testing
- Functional Testing
- Performance Testing
- Keyword Testing
- Data driven and Sanity Testing
Selenium testing tool is limited to:
- Perform testing on applications that are web-based only
- Cannot perform testing on windows based applications and mobile app
- Requires outside assistance to generate reports like Jenkins or TestNG
- Cannot perform testing on image-based applications and does not provides built-in IDE for the generation of test scripts
- Requires knowledge in scripting languages and Eclipse to write test scripts
Selenese is a cross-platform test scripting language used by Selenium to test web-based applications and fix bugs in software. It allows the user to develop test cases by providing a set of commands.
Selenium allows writing test scripts in any programming language like Selenese. Test scripts in Selenium are the set of commands.
Selenium includes various types of locators such as:
- Identifier (ID):
- Name
- Classname:
- Link Text and Partial Text
- DOM
- CSS path
- XPath
- UI-element
The Selenium can be integrated with a list of tools to execute tests continuously include:
- Maven
- Jenkins
- Docker
- TestNG
- JUnit
Selenium Assertion is used to test application and compare the actual outcome with expected outcome to confirm the application is working as per expectations. There are three kinds of assertions used in Selenium include:
- Assert
- Verify
- WaitFor
Both commands assert and verify in Selenium are aimed to check the given element is existed on the web page or not.
Assert Command:
The Assert in Selenium is used to verify 0061 specific condition is either true or false and aborts the execution of test steps when the condition fails. When the given condition is true, it continuous test and executes next line of code.
Verify Command:
The Verify command in Selenium also used to verify a specific condition is true or false. Unlike Assert, Verify continuous the execution of test steps even the condition is failed.
XPath is also known as XML path. It is an extensible markup language similar to HTML and is used to locate HTML elements across the webpage. It includes two types of strategies to locate an element on web pages such as XPath Absolute and XPath Attribute.
XPath Absolute: It allows the users to find an absolute XPath to find an element from the root node. It starts with forwarding slash “/”.
Syntax: Html/body/tag 1[index]/tag 2[index]/tag 3[index]/…/tag N[index]
Example:html/body/div[3]/section/div[1]/div/section/div[2]/div/fieldset/form/div[2]/div/input[2]/h2[1]
XPath Attribute: It is used when there are no suitable attributes to find the path of the required elements across web page.
The syntax of XPath is followed as:
XPath = //HTMLTagName@attributename=’value n’
Here HTMLTagName is tagname of a specific node, attributename is the attribute name of node and value is attribute value.
For example: //Form[@class=’Box’]
Selenium automation includes three wait types as Implicit, Explicit, and Fluent wait type.
Implicit: This type of wait tells Selenium Web Driver to wait for a specific duration of time before throwing an exception.
Explicit: This wait type tells Selenium Web Driver to wait for a specific or expected condition before it throws an exception.
Selenium Interview Questions and Answers for Beginners
Selenium Interview Questions and Answers for Beginners
There are 8 locators
Id , Name, classname, cssSelector, Xpath, TagName ,Linktext and PartialLinkText
Most Web pages have id and name properties as unique values and these should be used first for non-link items. For link items, linkText and partialLinkText are preferred. Next is Css Selector and xpath. These are least preferred because of the time taken to traverse the DOM to find elements.
Absolute path starts from the top of the DOM which means essentially starting from /html whereas Relative one can start from anywhere in the DOM and just matches the pattern. Also it always starts with //
WaitTimeOut Exception, No Such Element, StaleElementReference, ElementNotVisible Exception and NoAlertPresent Exception
Selenium 3.11
Data Driven – Where same actions are performed for different sets of data and the result is verified
Keyword Driven – Commonly reused functions are stored as keywords to be used in multiple tests
Hybrid – A Mixture of Data Driven and Keyword frameworks
Parent::tr will get the parent of the element with the tr tag.
Ancestor – This will get any parent and not just the immediate one.
Sibling – to identify elements with the same parent. The syntax is following-sibling::tr
Implicit wait is present for the entire duration of the driver instance. This is usually a small value like 5 or 10 seconds which is enough to wait for majority of the elements of the application.
Explicit wait is for elements which usually take more time to be visible than the majority of other application elements. Through the ExpectedCOnditions class, we can use many types of conditions as exit criteria for this wait.
Sample code :
WebDriverwait wait = new WebDriverwait (driver,10)
WebElement element = wait.until(ExpectedConditions.visibilityof(element))
Fluent wait is used when you need to add extra conditions like which exception to ignore while waiting and also specifying the polling interval
Sample code :
Wait wait2 = new FluentWait(driver)
.withTimeout(Duration.of(20, (TemporalUnit) TimeUnit.SECONDS))
.pollingEvery(Duration.of(1, (TemporalUnit) TimeUnit.SECONDS))
.ignoring(NoSuchElementException.class);
No. There is a concept called polling interval which means that the driver will look into the DOM at frequent intervals. The Default value is 0.5 seconds
When an element that was present in the DOM previously but due to an user action, which results in a page refresh, the element is no longer visible on the page.
We can use javascript and actions class
((JavascriptExecutor) driver).executeScript(“arguments[0].click();”, element);
Actions ab = new Actions(driver);
ab.moveToElement(element).click();
Actions ab = new Actions(driver);
ab.moveToElement(element);
Actions ab = new Actions(driver);
ab.moveToElement(element).doubleClick();
ab.moveToElement(element).contextClick();
TakesScreenshot ts = (TakesScreenshot) driver
File file = ts.getScreenshotas(OutputType.FILE)
FileUtils.CopyFile(file,”//c//folder”);
It is a simpler way to maintain your driver executables and their versions. Instead of downloading the drivers for each browser and setting their path in the code, we can just add the WebDriverManager dependency and it will ensure the latest drivers are downloaded.
Driver.switchTo().frame(either frame id or index)
driver.switchTo().defaultContent() to move to the original node.
Using Javascript
((JavascriptExecutor) driver).executeScript(“arguments[0].setAttribute(‘style’,’background:yellow’);”, element);
getWindowHandle returns a string value that is unique and points to the current window in focus.
getWindowHandles returns a Collection(Set) of all windows opened by this driver instance.
If there is only one window open both do the same thing. However in case of multiple windows, close closes only the focused window whereas quit closes all the windows.
String handle1 = driver.getWindowHandle()
Driver.findElement(by.id(”some link”)).click();
Set<String> habdles = driver.getWindowHandles();
For(String s : handles){
If(s != handle1)
Driver.close();
}
Src/main/java – Contains the reusable components like BaseTest and Parent Page class, Utilities(Excel and DB Utility), Page Objects for all the pages in the application and MainDriver script for running the tests
Src/test/java – Contains all the tests grouped under appropriate folders like Regression and Smoke.
Answer: An Interface can only have methods without any implementation. Since java 8 , an interface can have a method implementation with default keyword so as to enable interfaces to be flexible.
An Abstract class can have defined as well as abstract methods.
More thsn one interface can be implemented by a class whereas only one abstract class can be extended to a particular class
Abstraction – Method implementation of reusable methods need not be shown and can be used without knowing its details.
Encapsulation – Declaring local variables as private and those which needs to be used only by extending classes or package classes as protected. The latter is useful when you add components into jars as dependency
Inheritance – BaseTest and Page class are parent classes . All test classes inherit from the former and all Page objects inherit from the latter.
Polymorphism – The same class can have different forms with different values. For example the Homepage class can have multiple instances with different values initialized in the constructor.
No. Try can be followed with either catch alone or finally alone. Also try with resources does not need finally also.
Selenium with Java Interview Questions and Answers
Java is an High-level Object-oriented Programming language
Java is a fast, Secure ad reliable Programming language
Java is a platform independent because it is a ‘Write once Run Anywhere’, when we compile a java program it generates a class file which can run on any system or platform.
No, Java is not a pure object-oriented because it makes use of eight data types which are not objects
A class is blueprint or templatefrom which individual objects are created.
Object is an instance of a class, which describes the state and behaviour of a class.
Loops in java are used to execute a statement or block of statement repetadely for several times.
There are 3 diffrent types of loops in Java:
a. While loop
b. do while loop
c. for loop
Inheritance
Polymorphism
Encapsulation
Abstraction
Inheritance is one of the pillar of the oops, which lets the sub-class or child class to inherit the properties of Base class or Parent class.
Polymorphism is one of the pillar of the oops, in which object has the ability to take many forms.
Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts
Method overloading is the concept of Polymorphism where a class contains multiple method with same name but diffrent types of parameters or diffrent number of parameters.
Method overriding is the concept of Pilymorphism,
In Method Overriding, child class have the same method with same name and exactly the same number and type of parameters and same return type as a super class.
It always requires inheritance in Method Overriding
Constructor in Java is used to creat an Object that is an instance of a Class. Constructor name should be same as class name. Constructor don’t have any return type hence they don’t return any value
Local Variable:
These variables are declared inside the method and the varialbe will be destroyed once the compiler exists the method.
class Variabe:
These variables are declared inside the class but outside the method and it can be accessed any where inside the class.
Abstraction is the concept of Encapsulation which hides the implementation of internal details and showing functionality to the users.
Encapsulation is a mechanism of binding code and data together in a single unit
Q16. What is an Array?
Array in java is used to store multiple vaules into a single variable of same data type
Private: If the class or method or variable is declared as private it’s scope will be only with in the class
public: If the class or method or variable is declared as public it can be accessed anywhere within the class, package and outside the package
protected: If the method or variable is declared as protected it can be accessed only within a packages where it is declared
Array: Array in java is used to store multiple vaules into a single variable of same data type, once the size declared for array can’t be changed.
ArrayList: ArrayList in java is used to store multiple values into a single variable of diffrent type.
FileInputStream is class from the java I/O package which is used to read the data from the file.
FileInputStream is class from the java I/O package which is used to write the data into the file.
We can handle exception in Java using try-catch block.
public class FibonacciSeries {
public static void main(String args[]) {
int a = 0;
int b = 1;
int c;
int i;
int count = 10;
System.out.print(a);
for (i = 1; i < count; i++) {
c = a + b;
System.out.print(” ” + c);
a = b;
b = c;
}
}
}
import java.util.Scanner;
public class AddMatrix
{
public static void main(String args[])
{
int rows, cols, i, j;
Scanner in = new Scanner(System.in);
System.out.println(“Please Enter number of rows and columns”);
rows = in.nextInt();
cols = in.nextInt();
int first[][] = new int[rows][cols];
int second[][] = new int[rows][cols];
int sum[][] = new int[rows][cols];
System.out.println(“Please Enter elements of first matrix”);
for ( i = 0 ; i < rows ; i++ )
for ( j = 0 ; j < cols ; j++ )
first[i][j] = in.nextInt();
System.out.println(“Please Enter elements of second matrix”);
for ( i = 0 ; i < rows ; i++ )
for ( j = 0 ; j < cols ; j++ )
second[i][j] = in.nextInt();
for ( i = 0 ; i < rows ; i++ )
for ( j = 0 ; j < cols ; j++ )
sum[i][j] = first[i][j] + second[i][j];
System.out.println(“Sum of entered matrices:-“);
for ( i = 0 ; i < rows ; i++ )
{
for ( j = 0 ; j < cols ; j++ )
System.out.print(sum[i][j]+”\t”);
System.out.println();
}
}
}
public class SwapTwoNumbers {
public static void main(String[] args) {
int num1=55;
int num2=23;
System.out.println(“Before Swapping”);
System.out.println(“Value of number1 is :” + num1);
System.out.println(“Value of number2 is :” +num2);
num1=num1+num2;
num2=num1-num2;
num1=num1-num2;
System.out.println(“After Swapping”);
System.out.println(“Value of number1 is :” + num1);
System.out.println(“Value of number2 is :” +num2);
}
}
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
int num;
Scanner in = new Scanner(System.in);
System.out.println(“Please Enter a number”);
number=in.nextInt();
int sum=0 ;
while(num!=0){
sum=sum+(num%10);
num=num/10;
}
System.out.println(“Sum of Digits =”+sum);
}
Selenium is robust automation suite which is used for automating web based applications, It supports multiple browsers, Platforms and languages.
Selenium has four components
a. Selenium IDE: Selenium IDE is a record and playback tool. It is a firefox plugin.
b. Selenium RC: Selenium RC is a server that allows a user to create test scripts in the desired programming language.
c. Selenium WebDriver: WebDriver directly communicates with the browsers using API’s
d. Selenium Grid: Selenium Grid is used to run test cases on multiple platoforms and environments concurrently.
- Selenium supports only web based applications
b. captcha and Barcode can not be automated using selenium
c. We can generated reports only using third-party tools
id
name
classname
linktext
partiallinktext
cssSelector
tagname
xpath
/ – Refers absolute xpath
// – Refers relative xpath
- Free and open source
b. Cross-brower testing
c. Platform compatibility
d. Supports multiple programming languages
Soft Assert: Soft Assert does not throw any Excpetion when the assert fails the execution will continue
Hard Assert: Hard Assert throw exception when the assert fails and the execution will be terimanted.
NoSuchElementException
WebDriverException
TimeoutException
NoAlertPresentException
NoSuchWindowException
- Implicit Wait: This wait tells the WebDriver to wait for certain amount of time before throwing as Exception
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
b. Explicit Wait: This wait tells the WebDriver to wait for certain amount of time untill the expected condition
WebDriverWait wait = new WebDriverWait (driver, 20);
wait.until(ExpectedConditions.VisibilityofElementLocated(By.xpath(“”)));
c. Fluent Wait: FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.
By using the getText() method.
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
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
driver.manage().deleteAllCookies();
Using driver.getWindowHandle() and driver.getWindowHandles() method.
driver.close(): This method closes the browser which is currently opened by the WebDriver.
driver.quit(): This method closes all the browser which is opened by the WebDriver.
We can handle mouseover, doubleclick and draganddrop using the Action class.
Actions action = new Actions(driver);
action.moveToElement().build().perform();
action.dragAnddrop(source, destination).build().perform();
action.doubleClick().build().perform();
TestNG is a framework which is ispired by Junit and Nunit but provides more features than these two.
- TestNG provides parallel execution
b. It allows to assign priority to test methods
c. It allows grouping of test methods
d. It provides the pretty HTML Reports
BeforeTest
AfterTest
BeforeClass
AfterClass
BeforeMethod
AfterMethod
BeforeSuite
AfterSuite
BeforeGroups
AfterGroups
Test
- Using testng.xml we can execute multiple test cases in one go
b. Allows to add group dependencies
c. Allows to parameterize the test cases
d. Allows to execute multiple testcases on different browsers
Cucumber is a framework which is based on the Behavior Driven Development (BDD) methodology
A feature file provides a high-level description. The first line of the feature file must start with the keyword ‘Feature’ following the description of the application under test.
We can include multiple secenarios in one feature file.
- Cucumber is an open source tool.
b. Automation test cases developed using the Cucumber tool are easier to maintain
c. Easy to integrate with other tools such as Selenium
assertEqual
assertTrue
assertNotEqual
assertFalse
import org.testng.annotations.*;
public class PriorityTestCase{
@Test(priority=0)
public void testCase1() {
system.out.println(“TC 1”);
}
@Test(priority=1)
public void testCase2() {
system.out.println(“TC 2”);
}
}
importorg.junit.runner.RunWith;
importcucumber.api.CucumberOptions;
importcucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(features=”Features”,glue={“StepDefinition”})
public class Runner
{
}