Selenium Interview questions and answers
Selenium Tester Job Responsibilities
Job Responsibilities may vary from one company to another and one project to another, but I am covering this topic by considering several companies approaches.
Selenium Knowledge for Fresher or below 1 Year Experienced
• Basic Understanding of Functional and Regression Test Automation.
• Good knowledge on Selenium suite of Tools (Selenium IDE, Selenium RC, Selenium WebDriver and Selenium Grid).
• Knowledge of Java Programming (Data Types, Variables, Operators, Flow Control Statements, Methods (Built-in as well as User defined), Exception handling, File Handling, Excel file Operations, Database Operations and OOPS concepts).
• Good knowledge on Element Locators, Selenese Commands, WebDriver methods.
• Idea on Test Automation Framework implementation
• Ability to create and execute Test cases using Selenium IDE and Selenium Webdriver.
I) 1+ Years Experience in Test Automation using Selenium
• Understanding Test Requirements and analyzing the Application under Test(AUT).
• Generating Test Cases (Test Scripts) using Selenium Element locators and WebDriver Methods.
• Enhancing Test cases using Java programming.
• Debugging Test Cases and Fixing errors.
• Executing/Running Test Cases
• Defect Reporting & Tracking
• Test Reporting
--------------------------------------------------
II) 2+ years of Experience in Test Automation using Selenium
• Creating Test Automation Resources (Function Libraries etc...).
• Handling duplicate objects and dynamic objects using index property and Regular expressions.
• Collecting Test Data for Data Driven Testing.
• Creating Test Cases (Test Scripts) using Selenium Webdriver, Java and TestNG Annotations.
• Parameterization, Synchronization and define Test results.
• Debugging and Running Tests
• Analyzing Test Results
• Defect Reporting and Tracking using any Defect Management Tool.
• Test Reporting
• Modifying Tests and performing Re & Regression Testing.
--------------------------------------------------
III) 3+ years of Experience in Test Automation using Selenium
• Understanding and Analyzing the Application Under Test in terms of Object Identification.
• Creating Test scenarios and Collecting Test Data.
• Identifying end to end scenarios and code modularity.
• Implementing JUnit or TestNG Test Automation framework and developing automation infrastructure.
• Creating reusable components.
• Creating and enhancing Test Cases (Test Scripts) using Element locators, WebDriver methods, Java programming concepts and TestNG Annotations.
• Error Handling, Adding comments.
• Creating Data driven Tests and Running through framework.
• Cross Browser Testing (Executing test cases against various browsers like Mozilla Firefox, Google chrome, IE and Safari etc...).
• Parallel Test Execution.
• Defining and exporting Test Results.
• Analyzing Test Results and Reporting Defects.
• Tracking Defects and Select Test cases for Re & Regression Testing.
• Modifying Test Automation Resources and Maintenance of Resources.
Selenium Tester Job Responsibilities
Job Responsibilities may vary from one company to another and one project to another, but I am covering this topic by considering several companies approaches.
Selenium Knowledge for Fresher or below 1 Year Experienced
• Basic Understanding of Functional and Regression Test Automation.
• Good knowledge on Selenium suite of Tools (Selenium IDE, Selenium RC, Selenium WebDriver and Selenium Grid).
• Knowledge of Java Programming (Data Types, Variables, Operators, Flow Control Statements, Methods (Built-in as well as User defined), Exception handling, File Handling, Excel file Operations, Database Operations and OOPS concepts).
• Good knowledge on Element Locators, Selenese Commands, WebDriver methods.
• Idea on Test Automation Framework implementation
• Ability to create and execute Test cases using Selenium IDE and Selenium Webdriver.
I) 1+ Years Experience in Test Automation using Selenium
• Understanding Test Requirements and analyzing the Application under Test(AUT).
• Generating Test Cases (Test Scripts) using Selenium Element locators and WebDriver Methods.
• Enhancing Test cases using Java programming.
• Debugging Test Cases and Fixing errors.
• Executing/Running Test Cases
• Defect Reporting & Tracking
• Test Reporting
--------------------------------------------------
II) 2+ years of Experience in Test Automation using Selenium
• Creating Test Automation Resources (Function Libraries etc...).
• Handling duplicate objects and dynamic objects using index property and Regular expressions.
• Collecting Test Data for Data Driven Testing.
• Creating Test Cases (Test Scripts) using Selenium Webdriver, Java and TestNG Annotations.
• Parameterization, Synchronization and define Test results.
• Debugging and Running Tests
• Analyzing Test Results
• Defect Reporting and Tracking using any Defect Management Tool.
• Test Reporting
• Modifying Tests and performing Re & Regression Testing.
--------------------------------------------------
III) 3+ years of Experience in Test Automation using Selenium
• Understanding and Analyzing the Application Under Test in terms of Object Identification.
• Creating Test scenarios and Collecting Test Data.
• Identifying end to end scenarios and code modularity.
• Implementing JUnit or TestNG Test Automation framework and developing automation infrastructure.
• Creating reusable components.
• Creating and enhancing Test Cases (Test Scripts) using Element locators, WebDriver methods, Java programming concepts and TestNG Annotations.
• Error Handling, Adding comments.
• Creating Data driven Tests and Running through framework.
• Cross Browser Testing (Executing test cases against various browsers like Mozilla Firefox, Google chrome, IE and Safari etc...).
• Parallel Test Execution.
• Defining and exporting Test Results.
• Analyzing Test Results and Reporting Defects.
• Tracking Defects and Select Test cases for Re & Regression Testing.
• Modifying Test Automation Resources and Maintenance of Resources.
This post is mainly for people preparing for interviews.
Before posting Selenium Interview questions and answers let me clear that it totally depends on number of factors.
1- For which position you are applying.
2- Who is taking your interview?
3- For which company you are applying.
4- Does Interviewer’s themselves knows about automation or not?
You must be wondering why I am covering all these factors right. I have taken couple of interviews and based on my experience I will tell you what questions an Interviewer might ask.
If you are applying for Sr Automation Engg, Lead or Test Manager then be ready with some high-level topics, which anyways I will be covering in this post.
However, if you are applying as a fresher, then you should be ready with some Java program and some Selenium related code.
Before getting started keep in mind that there is not hard and fast rule that, the interviewer will ask questions from a specific domain. It might cover multiple domain/tools.
1- What is Selenium Webdriver, Selenium RC, Selenium IDE and Selenium Grid and which version you have used?
2-
Ans : Selenium Webdriver : WebDriver is a web automation tool that allows you to execute your tests against different browsers, not just Firefox (unlike Selenium IDE). It is faster tham the Selenium RC. Because it directly communicate with browser no need of external server like Selenium RC.
Selenium IDE :Selenium IDE (Integrated Development Environment) is the simplest tool in the Selenium Suite. It is a Firefox add-on that creates tests very quickly through its record-and-playback functionality.
Selenium RC :Selenium Remote Control (RC) is a test tool that allows you to write automated web application UI tests in any programming language against any HTTP website using any mainstream JavaScript-enabled browser.
Selenium Grid: Selenium Grid is a part of the Selenium Suite that specializes on running multiple tests across different browsers, operating systems, and machines in parallel.
************************------------------******************
3- Can you please explain Selenium Architecture?
1- Have you worked on different browsers? Have you ever performed Cross browser testing?
Ans: Yes, I have worked on different browsers like Mozilla (the most common), Chrome, and IE, performed cross browser testing demo. But while performing cross browser testing in my automation framework. It was getting slower and data would not be going on to the proper browser.
Ans- Every month a new browser is coming into market and it became very important to test our web application on different browser. Selenium supports Cross browser testing. Please check the detailed article here.
************************------------------******************
2- What type of test you have automated?
Ans- Automation mainly focuses on regression testing, smoke testing, Sanity Testing and some time you can for End to End test cases.
************************------------------******************
5- How many test cases you have automated per day?
Ans- It totally depends on your manual test cases. Sometimes we can automate 3-4 test cases per day which contain limited operation and some validation. Some test cases may take 1 day or more than one day as well.It totally depends on test case complexity.
************************------------------******************
6- How to work with Chrome, IE or any other third party driver? Why we need separate driver for them?
Ans- Selenium by default supports only Firefox browser so in order to work with Chrome and IE browser we need to download separate drivers for them and specify the path.
************************------------------******************
7- Have you created any framework? Which framework you have used? Ans. Yes. I have created Data-Driven Framework and added some functionalities of Hybrid framework and Page object model.
************************------------------******************
8- Can you please explainframework architecture? ************************------------------******************
9- What is POM (Page Object Model) and what is the need of it?
Ans- 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 doesn’t require us to change any tests, we just need to change only the code within the page objects (Only at one place). Many other tools which are using selenium, are following the page object model.
The Page Object model provides the following advantages.
1. There is clean separation between test code and page specific code such as locators (or their use if you’re using a UI map) and layout.2. There is single repository for the services or operations offered by the page rather than having these services scattered throughout the tests.
************************------------------******************
10- What are the challenges you have faced while automating your application?
Ans- Challenges faced that are as follows:
· Frequently changing UI. It always need to make changes in code most of the time.
· Stuck somewhere while running automation scripts in chrome browser getting error that element is not visible, element not found.
· New kind of element like ck-editor, bootstrap calendar and dynamic web tables. But get the solution always.
· Reused of test scripts.
· To be continued…….
************************------------------******************
11- What are the different type of exception available in Selenium? Have you faced any exception while automation?
Ans- Yes. I have faced lots of exception. List are as follows:
1. ElementNotSelectableException
2. ElementNotVisibleException
3. NoSuchAttributeException
4. NoSuchElementException
5. NoSuchFrameException
6. TimeoutException
7. Element not visible at this point
Ans: There are two types of alerts that we would be focusing on majorly:
- Windows based alert pop ups
- Web based alert pop ups
As we know that handling windows based pop ups is beyond WebDriver’s capabilities, thus we would exercise some third party utilities to handle window pop ups. Handling pop up is one of the most challenging piece of work to automate while testing web applications. Owing to the diversity in types of pop ups complexes the situation even more.
Generally JavaScript popups are generated by web application and hence they can be easily controlled by the browser.
Webdriver offers the ability to cope with javascript alerts using Alerts APIClick here to view Alert API Details
// Get a handle to the open alert, prompt or confirmation
Alert alert = driver.switchTo().alert();
Alert alert = driver.switchTo().alert();
Alert is an interface. There below are the methods that are used
//Will Click on OK button.
alert.accept();
alert.accept();
// Will click on Cancel button.
alert.dismiss()
alert.dismiss()
//will get the text which is present on th Alert.
alert.getText();
alert.getText();
//Will pass the text to the prompt popup
alert.sendkeys();
alert.sendkeys();
//Is used to Authenticate by passing the credentials
alert.authenticateUsing(Credentials credentials)
alert.authenticateUsing(Credentials credentials)
Example to handle alert in selenium Webdriver:
The below is the sample code for alerts, please copy and make an html file and pass it to the webdriver.
<html>
<head>
<title>Selenium Easy Alerts Sample </title>
</head><body>
<h2>Alert Box Example</h2>
<fieldset>
<legend>Alert Box</legend><p>Click the button to display an alert box.</p>
<button onclick="alertFunction()">Click on me</button>
<script>
functionalertFunction()
{
alert("I am an example for alert box!");
}
</script>
</fieldset>
</body>
</html>
The below program will demonstrate you working on Alerts popup using above html file.
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
publicclassPopupsHandling {
WebDriver driver=newFirefoxDriver();
@Test
publicvoidExampleForAlert() throws InterruptedException
{
driver.manage().window().maximize();
driver.get("file:///C:/path/alerts.html");
Thread.sleep(2000);
driver.findElement(By.xpath("//button[@onclick='alertFunction()']")).click();
Alert alert=driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
}
}
************************------------------******************
13- How to handle multiple windows in Selenium?
Ans:
When we have multiple windows in test automation, all we need to do is switching the focus from one window to another. Let us understand the same in the following way:
Window A has a link "Link1" and we need to click on the link (click event).
Window B displays and we perform some actions.
The entire process can be fundamentally segregated into following steps:
Step 1 : Clicking on Link1 on Window A
A new Window B is opened.
Step 2 : Save reference for Window A
Step 3 : Create reference for Window B
Step 3 : Move Focus from Window A to Window B
Window B is active now
Step 3 : Perform Actions on Window B
Complete the entire set of Actions
Step 4 : Move Focus from Window B to Window A
Window A is active now
Let us understand the same with a small coding example.
Selenium Interview Questions Real Time import java.util.List;
import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class MultipleWindowsHandle { WebDriver driver; @Before public void setup() throws Exception { driver=new FirefoxDriver(); String URL="http://www.seleniummaster.com"; driver.get(URL); driver.manage().window().maximize(); } @Test public void test() throws Exception { // Opening site driver.findElement(By.xpath("//img[@alt='SeleniumMasterLogo']")).click(); // Storing parent window reference into a String Variable String Parent_Window = driver.getWindowHandle(); // Switching from parent window to child window for (String Child_Window : driver.getWindowHandles()) { driver.switchTo().window(Child_Window); // Performing actions on child window driver.findElement(By.id("dropdown_txt")).click(); List dropdownitems=driver.findElements(By.xpath("//div[@id='DropDownitems']//div")); int dropdownitems_Size=dropdownitems.size(); System.out.println("Dropdown item size is:"+dropdownitems_Size); ((WebElement) dropdownitems.get(1)).click(); driver.findElement(By.xpath("//*[@id='anotherItemDiv']")).click(); } //Switching back to Parent Window driver.switchTo().window(Parent_Window); //Performing some actions on Parent Window driver.findElement(By.className("btn_style")).click(); } @After public void close() { driver.quit(); } }
14- Have you ever worked on frames? In addition, how to handle frames in Selenium?
Yes. In Selenium to work with iFrames, we have different ways to handle frame depending on the need.
Please look at the below ways of handling frames.
driver.switchTo().frame(int arg0);
Select a frame by its (zero-based) index. That is, if a page has multiple frames (more than 1), the first frame
would be at index "0", the second at index "1" and so on. Once the frame is selected or navigated , all subsequent calls on the WebDriver interface are made to that frame. i.e the driver focus will be now on the frame. Whatever operations we try to perform on pages will not work and throws element not found as we navigated / switched to Frame.
Example: if iframe id=webklipper-publisher-widget-container-frame, it can be written as
driver.switchTo().frame("webklipper-publisher-widget-container-frame"); Below is the code snippet to work with switchToFrame using frame id.
Code:
publicvoidswitchToFrame(int frame) { try { driver.switchTo().frame(frame); System.out.println("Navigated to frame with id " + frame); } catch (NoSuchFrameException e) { System.out.println("Unable to locate frame with id " + frame + e.getStackTrace()); } catch (Exception e) { System.out.println("Unable to navigate to frame with id " + frame + e.getStackTrace()); } }
driver.switchTo().frame(WebElement frameElement);
Some times when there are multiple Frames (Frame in side a frame), we need to first switch to the parent frame and then we need to switch to the child frame. below is the code snippet to work with multiple frames.
public void switchToFrame(String ParentFrame, String ChildFrame) {
try { driver.switchTo().frame(ParentFrame).switchTo().frame(ChildFrame); System.out.println("Navigated to innerframe with id " + ChildFrame + "which is present on frame with id" + ParentFrame); } catch (NoSuchFrameException e) { System.out.println("Unable to locate frame with id " + ParentFrame + " or " + ChildFrame + e.getStackTrace()); } catch (Exception e) { System.out.println("Unable to navigate to innerframe with id " + ChildFrame + "which is present on frame with id" + ParentFrame + e.getStackTrace()); } }
After working with the frames, main important is to come back to the web page. if we don't switch back to
the default page, driver will throw an exception. Below is the code snippet to switch back to the default content.
public void switchtoDefaultFrame() { try { driver.switchTo().defaultContent();
System.out.println("Navigated back to webpage from frame"); } catch (Exception e) { System.out .println("unable to navigate back to main webpage from frame" + e.getStackTrace()); } }
************************------------------******************
15- What are different locators available in Selenium?
Ans- There are 8 types of locators are available in selenium that are as follows:
id, xpath, name, byClassName, css selector, byTagName, linkText, partialLinkText.
************************------------------******************
16- Can you please explain XPATH and CSS technique? How to handle dynamic changing elements?
CSS Selector:
CSS mainly used to provide style rules for the web pages and we can use for identifying one or more elements in the web page using css. If you start using css selectors to identify elements, you will love the speed when compared with XPath. Check this for more details on Css selectors examples
We can you use Css Selectors to make sure scripts run with the same speed in IE browser.
CSS selector is always the best possible way to locate complex elements in the page.
XPath Selector:
XPath is designed to allow the navigation of XML documents, with the purpose of selecting individual elements, attributes, or some other part of an XML document for specific processing
There are two types of xpath
1. Native Xpath, it is like directing the xpath to go in direct way. like
Example: html/head/body/table/tr/td
Here the advantage of specifying native path is, finding an element is very easy as we are mention
the direct path. But if there is any change in the path (if some thing has been added/removed) then that xpath will break.
2. Relative Xpath.
In relative xpath we will provide the relative path, it is like we will tell the xpath to find an element by telling the path in between. Advantage here is, if at all there is any change in the html that works fine, until unless that particular path has changed. Finding address will be quite difficult as it need to check each and every node to find that path. Example: //table/tr/td
Dynamic CSS Selector in Selenium using multiple ways
Difference between CSS selector and xpath
Symbol used while writing css selector
Examples :
o Find css selector using single attribute. Syntax- tagname[attribute='value'] , Example- input[id='user_login']
o Css selector using multiple attribute:Syntax-tagname[attribute1='value1'][attribute2='value2']
o Find css using id and class name. Syntax for id: tagname#id, syntax for class: tagname.className
o Find css using contains. Syntax : tagname[attribute*=’value’]
o Find css using start-with. Syntax: tagname[attribute^=’value’]
o Find css using end-with. Syntax: tagname[attribute$=’value’]
Xpath Examples :
o Using multiple attribute. Syntax: //tagname[@attribute1=’value1’][attribute2=’value2’], Example: //a[@id=’id1’][@name=’namevalue1’] , //img[@src=’’][@href=’’].
o Using single attribute. Syntax: // tagname[@attribute-name=’value1’] , Example: // a [@href=’http://www.google.com’] , //input[@id=’name’] , //input[@name=’username’]
o Using contains method. Syntax: //tagname[contains(@attribute,’value1’)], Example: //input[contains(@id,’’)] , //input[contains(@name,’’)] , //a[contains(@href,’’)] , //img[contains(@src,’’)] , //div[contains(@id,’’)]
o Using starts with. Syntax: //tagname[starts-with(@attribute-name,’’)] , Example: //id[starts-with(@id,’’)]
o Using following node. Syntax: //input[@id=’’]/following::input[1]
o Using preceding node. Syntax: //input[@id=’’]/ preceding::input[1]
************************------------------******************
Ans- We have different Boolean methods for enable / disable, checked / unchecked and displayed / not
displayed that are as follows:
1. There's a method "isEnabled()", that checks whether a WebElement is enabled or not.
You can use the below code to check for that;
2. to check whether the checkbox is checked/selected or not, you can use "isSelected()" method,
which you can use like this;
************************------------------******************
18- How to work with dropdown?
Ans- WebDriver’s support classes called “Select”, which provides useful methods for interacting with select
options. User can perform operations on a select dropdown and also de-select operation using the below methods.
We can select or deselect option in dropdown by using following methods.
Syntax:
Select Se=new Select(element);
Se.selectByIndex(index);
Se.selectByvalue(value);
Se.selectByVisibleText(text);
We can also deselect the item using same thing that is just above method like.
************************------------------******************
19- Have you worked with Web table (Calendar)? If yes, then what was your approach.
Ans- Yes. First need to analysis its web page html code for this element. To find which type of calendar is,
then you can decide you can solve this calendar by using selenium Webdriver or using JavaScript executer. It all depends on the scenario the code. Now a day, there would be no. of new type of calendar are using by dev teams. We can’t handle these by using selenium but using JavaScript executer we get solution.
************************------------------******************
20- Can you tell me some navigation commands?
Ans- To access the navigation’s method, just type driver.navigate().. The intellisence feature of eclipse will
automatically display all the public methods of Navigate Interface.
Command - driver.navigate().to(appUrl);
It does exactly the same thing as the driver.get(appUrl) method. Where appUrl is the website address to load.
It is best to use a fully qualified URL.
forward() : void – This method does the same operation as clicking on the Forward Button of any browser.
It neither accepts nor returns anything.
Command - driver.navigate().forward();
Takes you forward by one page on the browser’s history.
back() : void – This method does the same operation as clicking on the Back Button of any browser.
It neither accepts nor returns anything.
Command - driver.navigate().back();
Takes youback by one page on the browser’s history.
refresh() : void – This method Refresh the current page. It neither accepts nor returns anything.
Command - driver.navigate().refresh();
Perform the same function as pressing F5 in the browser.
************************------------------******************
21- Difference between QUIT and Close?
Ans- driver.close and driver.quit are two different methods for closing the browser session in Selenium
WebDriver. Understanding both of them and knowing when to use which method is important in your test execution. Therefore, in this article, we have tried to throw light on both these methods.
o driver.close – It closes the the browser window on which the focus is set.
o driver.quit – It basically calls driver.dispose method which in turn closes all the browser windows
and ends the WebDriver session gracefully.
You should use driver.quit whenever you want to end the program. It will close all opened browser
window and terminates the WebDriver session. If you do not use driver.quit at the end of program, WebDriver session will not close properly and files would not be cleared off memory. This may result in memory leak errors.
************************------------------******************
22- Can you find the number of links available on Webpage?
Ans- Step to follow…
1) Navigate to the interested webpage for e.g. www.toolsqa.com.
2) Create a list of type WebElement to store all the Link elements in to it.
3) Collect all the links from the webpage. All the links are associated with the Tag ‘a‘.
22- Can you find the number of links available on Webpage?
Ans- Step to follow…
1) Navigate to the interested webpage for e.g. www.toolsqa.com.
2) Create a list of type WebElement to store all the Link elements in to it.
3) Collect all the links from the webpage. All the links are associated with the Tag ‘a‘.
4) Now iterate through every link and print the Link Text on the console screen.
|
59- What is priority feature in TestNG? In addition, how we can use this?
Ans:
1. In TestNG "Priority" is used to schedule the test cases. When there are multiple test cases, we want to execute test cases in order.
2. In order to achive, we use need to add annotation as @Test(priority=??). The default value will be zero for priority.
3. If we define priority as "priority=", these test cases will get executed only when all the test cases which don't have any priority as the default priority will be set to "priority=0".
Eg. The below examples shows using the priority for test cases.
public class testNGPriorityExample {
@Test public void registerAccount(){
System.out.println("First register your account"); } @Test(priority=2) public void sendEmail(){ System.out.println("Send email after login"); } @Test(priority=1) public void login(){ System.out.println("Login to the account after registration");}}
************************------------------*****************
60- What is dependsOnMethods and depends on group feature in TestNG? Ans: DependsOnMethods: Sometimes it may be required for a test method to depend upon multiple other methods. This feature is very well supported by TestNG as part of the dependency support.
Code:
public class DependentTestExamples {
@Test(dependsOnMethods = { "testTwo", "testThree" }) public void testOne() { System.out.println("Test method one"); } @Test public void testTwo() { System.out.println("Test method two");}
@Test public void testThree() { System.out.println("Test method three"); }}
The preceding test class contains three test methods which print a message name onto the console when executed. Here test method testOne depends on test methods testTwo and testThree. This is configured by using the attribute dependsOnMethods while using the Test annotation.
Depends on group: Similar to dependent methods TestNG also allows test methods to depend on groups. This makes sure that a group of test methods get executed before the dependent test method.
Code:
public class DependentTestExamples{
@Test(dependsOnGroups = { "test-group" }) public void groupTestOne() { System.out.println("Group Test method one"); } @Test(groups = { "test-group" }) public void groupTestTwo() { System.out.println("Group test method two"); } @Test(groups = { "test-group" }) public void groupTestThree() { System.out.println("Group Test method three");}}
The preceding test class contains two test methods which print a message name onto the console when executed. Here, test method testOne depends on test method testTwo. This is configured by using the attribute dependsOnMethods while using the Test annotation.
************************------------------*****************
61- What is testng.xml file in TestNG? Ans: In testng.xml file we can specify multiple name (s) which needs to be executed. In a project there may be many classes, but we want to execute only the selected classes. We can pass class names of multiple packages also. If say suppose, we want to execute two classes in one package and other class from some other package. The below is the example testng.xml which will execute the class names that are specified.
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. In the above xml, we have specified class name as “com.first.example.demoOne” and “com.first.example.demoOne” which are in “com.first.example” package. And class name demoThree is in package “com.second.example.” All the classes specified in the xml will get executes which have TestNG annotations. Below are the two example classes under “com.first.example” package which is executed.
public class demoOne { @Test public void firstTestCase(){ System.out.println("im in first test case from demoOne Class"); } @Test public void secondTestCase(){ System.out.println("im in second test case from demoOne Class");}}
We need to run the testng.xml file. (Right click on testng.xml and select Run as ‘TestNG Suite”)
************************------------------*****************
62- How to group test cases in TestNG? Ans: TestNG allows us to perform sophisticated groupings of test methods. Using TestNG can we can execute only set of groups while excluding another set. This gives us the maximum flexibility in divide tests and doesn't require us to recompile anything if you want to run two different sets of tests back to back. Groups are specified in testng.xml file and can be used either under the or tag. Groups specified in the tag apply to all the tags underneath.
Code:
public class groupExamples {
@Test(groups="Regression") public void testCaseOne() { System.out.println("Im in testCaseOne - And in Regression Group"); } @Test(groups="Regression") public void testCaseTwo(){ System.out.println("Im in testCaseTwo - And in Regression Group"); } @Test(groups="Smoke Test") public void testCaseThree(){ System.out.println("Im in testCaseThree - And in Smoke Test Group"); } @Test(groups="Regression") public void testCaseFour(){ System.out.println("Im in testCaseFour - And in Regression Group"); }}
The below is the XML file to execute, the test methods with group. We will execute the group “Regression” which will execute the test methods which are defined with group as “Regression”
<?xml version="1.0" encoding="UTF-8"?> <suite name="Sample Suite"> <test name="testing"> <groups> <run> <include name="Regression"/> </run> </groups> <classes><class name="com.example.group.groupExamples" /></classes></test></suite>
************************------------------*****************
63- How to execute multiple test cases in Selenium? Ans: TestNG provides an option to execute multiple tests in a single configuration file (testng.xml). It allows to divide tests into different parts and group them in a single tests. We can group all the tests related to database into one group, Regression tests in one group. And all the test cases related to Unit test cases into one group and so on. In testng.xml file we can specify multiple name (s) which needs to be executed. In a project there may be many classes, but we want to execute only the selected classes. We can pass class names of multiple packages also. If say suppose, we want to execute two classes in one package and other class from some other package.Code:
<?xml version="1.0" encoding="UTF-8"?> <suite name="Sample Suite" verbose="1" > <test name="Unit Level Test" ><classes> <class name=”com.easy.entry.AddTestCase" /><class name=”com.easy.entry.EditTestCase" /> </classes></test> <test name="Regression Test"> <classes> <class name=”com.easy.records.AddUserTestCase" /><class name=”com.easy.records.DeleteUserTestCase" /></classes></test></suite>************************------------------*****************
64- How to execute parallel test cases in Selenium? Ans: TestNG provides an ability to run test methods, test classes and tests in parallel. By using parallel execution, we can reduce the 'execution time' as tests are started and executed simultaneously in different threads. In testNG we can achieve parallel execution by two ways. One with testng.xml file and we can Configure an independent test method to run in multiple threads. First let us look at basic example for Parallel Execution of Test Methods using testng.xml. We will create a class with Two test methods and try to execute in different threads.
public class TestParallelOne { @Test public void testCaseOne() { //Printing Id of the thread on using which test method got executed System.out.println("Test Case One with Thread Id:- "+ Thread.currentThread().getId()); }@Test public void testCaseTwo() { //Printing Id of the thread on using which test method got executed System.out.println("Test Case two with Thread Id:- "+ Thread.currentThread().getId()); }}
The below is the simple testng.xml file, if you observe, we are defining two attributes 'parallel' and 'thread-count' at suite level. As we want test methods to be executed in parallel, we have provided 'methods'. And 'thread-count' attribute is to use to pass the number of maximum threads to be created.
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"><suite name="Parallel test suite" parallel="methods" thread-count="2"><test name="Regression 1"> <classes> <class name="com.parallel.TestParallelOne"/> </classes></test> </suite>************************------------------*****************
65- What is TestNG listener? Ans: A TestNG listener always extends the marker interface org.testng.ITestNGListener. Using listeners, one can extend TestNG in their dealings with notifications, reports and test behavior. Below are the listeners that TestNG provides:
IExecutionListener
IAnnotationTransformer
ISuiteListener
ITestListener
IConfigurationListener
IMethodInterceptor
IInvokedMethodListener
IHookable
IReporter
************************------------------*****************
66- What is Data provider in TestNG?
Ans-An important features provided by TestNG is the DataProvider feature. It helps you to write data-driven tests, which essentially means that same test method can be run multiple times with different data-sets. Please note that DataProvider is the second way of passing parameters to test methods (first way we already discussed in @Parameters example). It helps in providing complex parameters to the test methods as it is not possible to do this from XML.
To use the DataProvider feature in your tests you have to declare a method annotated by
@DataProvider
and then use the said method in the test method using the ‘dataProvider‘ attribute in the Test annotation.
1) Using @DataProvider and Test in Same Class
The below test class contains a test method which takes one argument as input and prints it to console when executed. A DataProvider method is also available in the same class by using the @DataProvider annotation of TestNG. The name of the said DataProvider method is mentioned using the name attribute of the@DataProvider annotation. The DataProvider returns a double Object class array with two sets of data i.e. “data one” and “data two”.
publicclassSameClassDataProvider
{
@DataProvider(name = "data-provider")
publicObject[][] dataProviderMethod() {
returnnewObject[][] { { "data one"}, { "data two"} };
}
@Test(dataProvider = "data-provider")
publicvoidtestMethod(String data) {
System.out.println("Data is: "+ data);
}
}
Now run above test. Output of above test run is given below:
Data is: data one
Data is: data two
PASSED: testMethod("data one")
PASSED: testMethod("data two")2) Using @DataProvider and Test in Different Class
DataProvider.java
publicclassDataProviderClass
{
@DataProvider(name = "data-provider")
publicstaticObject[][] dataProviderMethod()
{
returnnewObject[][] { { "data one"}, { "data two"} };
}
}
TestClass.java
importorg.testng.annotations.Test;
publicclassTestClass
{
@Test(dataProvider = "data-provider", dataProviderClass = DataProviderClass.class)
publicvoidtestMethod(String data)
{
System.out.println("Data is: "+ data);
}
}
Now run above test. Output of above test run is given below:
Data is: data one
Data is: data two
PASSED: testMethod("data one")
PASSED: testMethod("data two")
************************------------------*****************
67- How to disable particular test case?
Ans-Just add an attribute enabled=false in test declaration annotation. Ex: @Test(enabled=false)
************************------------------*****************
68- How to generate reports in TestNG?
Ans- We just need to run an annotated TestNG annotation scripts and refresh the project you can see the test-output folder is generated in project explorer. Just click on to it, and then click on to the emailable-report.html you can view the testNG report in HTML format
************************------------------*****************
69- How to generate log in TestNG?
Ans-Reporter is a separate class in TestNG that is available under org.testng package.In Selenium you can specify steps, which we are performing so that we can check our output, and in case any issue we can debug at which point our test cases failed.We can see the logs in report.
Code:
public class ReporterDemo {
@Test
public void testReport(){
WebDriver driver=new FirefoxDriver();
Reporter.log("Browser Opened");
driver.manage().window().maximize();
Reporter.log("Browser Maximized");
driver.get("http://www.google.com");
Reporter.log("Application started");
driver.quit();
Reporter.log("Application closed");
}
}
************************------------------*****************
70- How to execute only failed test cases in Selenium?
Ans-We can achieve this thing by using IRetryAnalyer Interface.
Code:
// implement IRetryAnalyzer interface
public class Retry implements IRetryAnalyzer{
// set counter to 0
int minretryCount=0;
// set maxcounter value this will execute our test 3 times
int maxretryCount=2;
// override retry Method
public boolean retry(ITestResult result) {
// this will run until max count completes if test pass within this frame it will come out of for loop
if(minretryCount<=maxretryCount)
{
// print the test name for log purpose
System.out.println("Following test is failing===="+result.getName());
// print the counter value
System.out.println("Retrying the test Count is=== "+ (minretryCount+1));
// increment counter each time by 1
minretryCount++;
return true;
}
return false;
}
}
Now we are done almost only we need to specify this in the test case.
@Test(retryAnalyzer=Retry.class)
In above statement, we are giving instruction to our test case that if the test case fails then it will call Retry class that we created above.
************************------------------*****************
Now if an interviewer having good knowledge on Selenium and have worked on different tools then be ready with other question too that will be related to Selenium only.
We have so many tools in market that we can integrate with Selenium like Maven, Sikuli, Jenkins, AutoIT, Ant and so on.
I will try to summarize question-based on the tools, which I have used.
Maven
71- Can you please explain what is apache maven and Apache ant?
Ans- Apache Maven:Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project's build, reporting and documentation from a central piece of information.
Apache Ant:Apache Ant is a Java library and command-line tool whose mission is to drive processes described in build files as targets and extension points dependent upon each other. The main known usage of Ant is the build of Java applications. Ant supplies a number of built-in tasks allowing to compile, assemble, test and run Java applications. Ant can also be used effectively to build non Java applications, for instance C or C++ applications. More generally, Ant can be used to pilot any type of process which can be described in terms of targets and tasks.
************************------------------*****************
72- Do you have used Maven project in your organization? If yes, then have you created build to execute your test?
Ans- No I don’t create maven project for company. But I have created demo for it.
************************------------------*****************
75- Can you please explain Maven life cycle?
Ans-
************************------------------*****************
Sikuli
76- Have you heard of Sikuli? If yes, can you please explain what exactly Sikuli does?
Ans: Sikuli automates anything you see on the screen. It uses image recognition to identify and control GUI components. It is useful when there is no easy access to a GUI's internal or source code.
************************------------------*****************
78- Advantage of Sikuli, Limitation of Sikuli.
Ans- 1. Sikuli is open source. 2. Sikuli IDE gives enough API's to interact with desktop based applications. Adding on to that we can use most of the API's of python scripting as well. Which totally depends upon how we code basically.
3. Image/Picture recognition in case of Sikuli is pretty much accurate. If we want more accuracy, we have to specify the regions of the images on the screen properly (This solves the problem of identification of small images on the screen). 4. Pretty much useful if the application demands so much of interaction from the user. 5. Behavior part of an application can be effectively analyzed. 6. We can easily identify the application crashes and bugs if we write script efficiently. 7. We can easily perform Boundary values testing of an application, which again depends on the scripting. 8. One of the biggest advantage of Sikuli is that, it can easily automate Flash objects. 9. makes easy to automate windows application.
Cons: 1. Running of batch wise sikuli scrips is little tricky and will not work some times in case we have 10 sikuli scripts and if we want to run them one by one automatically. 2. sikuli IDE hangs often and some time doesnt even gets opened untill we clear the registry. 3. sikuli is resolution dependent. (Which means the script written in 1366 * 768 screen resolution might not work in other resolutions).
4. sikuli scripting is platform dependent. 5. Error handling during run time has to be taken care properly in scripting if we run the scripts for long time.
************************------------------*****************
79- How to integrate Sikuli with Selenium script?
Ans-Step #1: Create a new Java Project in eclipse by clicking New -> Java project.Step #2:Right click on the Project Go to Build Path -> Configure Build Path.Switch to Libraries Tab. Click on “Add External Jars” and Add Selenium library jars as well as Sikuli-scritp.jarStep #3:Create a package inside src/ folder and create a class under that package.Eg.
import org.junit.Test; import org.openqa.selenium.WebDriver;import org.openqa.selenium.firefox.FirefoxDriver; import org.sikuli.script.App;import org.sikuli.script.FindFailed; import org.sikuli.script.Pattern;import org.sikuli.script.Screen;
public class sikuliFirstTest { @Test public void functionName() throws FindFailed {
// Create a new instance of the Firefox driver WebDriver driver = new FirefoxDriver();
// And now use this to visit Google driver.get("http://www.google.com"); //Create and initialize an instance of Screen object Screen screen = new Screen(); //Add image path Pattern image = new Pattern("C:\\searchButton.png"); //Wait 10ms for image screen.wait(image, 10); //Click on the image screen.click(image); }}
************************------------------*****************
80- Can you tell us the scenario where you have used Sikuli with Selenium?
Ans- 1) Here the scenario is to identify the “I’m Feeling Lucky” button and to click it using Sikuli.
Open Google home page from your browser and Capture “I’m Feeling Lucky” button using any screen capturing tool and save it to your local machine.
Note: Please don’t change the image by highlighting it or by editing. If you do so, then Sikuli may throw an error like “Can’t find image on the screen”.
************************------------------*****************
Jenkins
This is very vast topic and very interested but as an automation tester you will use it based on requirement
81- What is CI (Continuous integration) and what are different tools available in market.
Ans-Continuous Integration (CI) is a development practice that requires developers to integrate code into a shared repository several times a day. Each check-in is then verified by an automated build, allowing teams to detect problems early.
Tools available for continues integration are as follow:
1. Jenkins
2. Buildbot
3. Travis CI
4. Strider
5. Go
6. Integrity
************************------------------*****************
82- How to integrate Jenkins with Selenium?
Ans-1. Open your web browser and then Navigate to Below URL http://jenkins-ci.org this is the official website of Jenkins. 2. Now download Jenkins.war file and save it. 3. Go to location where Jenkins.war is available. 4. Step 2- Open Command prompt knows as CMD and navigate till project home directory and Start Jenkins server Start- cmd> Project_home_Directory> java -jar jenkins.war 5. Open any browser and type the url http://localhost:8080 6. Click on > Manage Jenkins 7. Click on Configure System, Navigate to JDK section and Click on Add JDK button, Uncheck Install automatically check box so Jenkins will only take java which we have mention above. 8. Give the name as JAVA_HOME and Specify the JDK path 9. Part 3- Execute Selenium build using Jenkins 10.Part 4-Schedule your build in Jenkins for periodic execution
************************------------------*****************
83- How to schedule test cases for nightly execution?
Ans-Open Task Scheduler by clicking the Start button Picture of the Start button, clicking Control Panel, clicking System and Security, clicking Administrative Tools, and then double-clicking Task Scheduler. Administrator permission required If you're prompted for an administrator password or confirmation, type the password or provide confirmation.
o Click the Action menu, and then click Create Basic Task.
o Type a name for the task and an optional description, and then click Next.
o Do one of the following:
o To select a schedule based on the calendar, click Daily, Weekly, Monthly, or One time, click Next; specify the schedule you want to use, and then click Next.
o To select a schedule based on common recurring events, click When the computer starts or When I log on, and then click Next.
o To select a schedule based on specific events, click When a specific event is logged, click Next; specify the event log and other information using the drop-down lists, and then click Next.
o To schedule a program to start automatically, click Start a program, and then click Next.
o Click Browse to find the program you want to start, and then click Next.
o Click Finish.
************************------------------*****************
84- Can you send email through Jenkins?
Ans- Yes.
§ install Email-ext plugin
§ Install Email-ext plugin at plug-in install page of JenkinsConfigure System“Jenkins Location” section
§ Enter valid email address to “System Admin e-mail address”“Extended E-mail Notification” section
§ Enter your email address to “Default Recipients” “E-mail Notification” section
§ Enter your SMTP server name to “SMTP server”
§ Click “Advanced”
§ Click “Use SMTP Authentication”
§ Enter required information’s
§ Check “Test configuration by sending test e-mail”
§ Click “Test configuration” to send test email
§ Click “Save” in the bottom of the page
§ Configure a project to send email at every build
§ Click “Add post-build action”
§ Click “Editable Email Notification”
§ Click “Advanced Settings…”
§ Click “Add Trigger”
§ Click “Always”
§ Save
§ Test-run
§ Click “Build Now”
§ Check Console output and received email
************************------------------*****************
85-Jenkins master slave concept and so on?
Ans-A "master" operating by itself is the basic installation of Jenkins and in this configuration the master handles all tasks for your build system. In most cases installing a slave doesn't change the behavior of the master. It will serve all HTTP requests, and it can still build projects on its own. Once you install a few slaves you might find yourself removing the executors on the master in order to free up master resources (allowing it to concentrate resources on managing your build environment) but this is not a necessary step. If you start to use Jenkins a lot with just a master you will most likely find that you will run out of resources (memory, CPU, etc.). At this point you can either upgrade your master or you can setup slaves to pick up the load. As mentioned above you might also need several different environments to test your builds. In this case using a slave to represent each of your required environments is almost a must.
A slave is a computer that is set up to offload build projects from the master and once setup this distribution of tasks is fairly automatic. The exact delegation behavior depends on the configuration of each project; some projects may choose to "stick" to a particular machine for a build, while others may choose to roam freely between slaves. For people accessing your Jenkins system via the integrated website (http://yourjenkinsmaster:8080), things work mostly transparently. You can still browse javadoc, see test results, download build results from a master, without ever noticing that builds were done by slaves. In other words, the master becomes a sort of "portal" to the entire build farm. Since each slave runs a separate program called a "slave agent" there is no need to install the full Jenkins (package or compiled binaries) on a slave. There are various ways to start slave agents, but in the end the slave agent and Jenkins master needs to establish a bi-directional communication link (for example a TCP/IP socket.) in order to operate.
************************------------------*****************
Random Questions
86- What is robot class and where have we used this in Selenium?
Ans- robot class is a class of java programming. It uses to facilitate automated testing of java platform implementations. It provides no. of methods to fire windows keyboard and mouse events. Syntax and example are as follows:
Some commonly and popular used methods of Robot API during web automation:
-need to create object of robot class :Robot robot=new Robot();
· keyPress(): Example: robot.keyPress(KeyEvent.VK_DOWN) : This method with press down arrow key of Keyboard
· mousePress() : Example : robot.mousePress(InputEvent.BUTTON3_DOWN_MASK) : This method will press the right click of your mouse.
· mouseMove() : Example: robot.mouseMove(point.getX(), point.getY()) : This will move mouse pointer to the specified X and Y coordinates.
· keyRelease() : Example: robot.keyRelease(KeyEvent.VK_DOWN) : This method with release down arrow key of Keyboard
· mouseRelease() : Example: robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK) : This method will release the right click of your mouse
In certain Selenium Automation Tests, there is a need to control keyboard or mouse to interact with OS windows like Download pop-up, Alerts, Print Pop-ups, etc. or native Operation System applications like Notepad, Skype, Calculator, etc. Selenium Webdriver cannot handle these OS pop-ups/applications.
************************------------------*****************
87- Be ready with some basic Java programs which every automation Engg should know
Like string reverse, count the number of characters in a given string and so on.
If you will apply for Amazon, Flipkart then make sure you know Data structure very well because question level will be very high.
************************------------------*****************
88- List down all locator with performance.
Ans-As per performance of locator from top to bottom.
id - >Select element with the specified @id attribute.
Name - >Select first element with the specified @name attribute.
Linktext - >Select link (anchor tag) element which contains text matching the specified link text
Partial Linktext - >Select link (anchor tag) element which contains text matching the specified partial link text
Tag Name - >Locate Element using a Tag Name .
Class name - >Locate Element using a Tag Name ..
Css - >Select the element using css selectors. You can check here for Css examples and You can also refer W3C CSS Locatros
Xpath - >Locate an element using an XPath expression.
************************------------------*****************
89- Find broken links on Web page.
Ans: Scenario for find broken links using selenium
Before jumping to the code let’s take one simple example to get the actual concept.
Example1- Suppose we have one application which contains 400 links and we need to verify the link is broken or not.
Program for finding broken links
public class VerifyLinks {
public static void main(String[] args)
{
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.google.co.in/");
List<WebElement> links=driver.findElements(By.tagName("a"));
System.out.println("Total links are "+links.size());
for(int i=0;i<links.size();i++)
{
WebElement ele= links.get(i);
String url=ele.getAttribute("href");
verifyLinkActive(url);
}
}
public static void verifyLinkActive(String linkUrl){
try
{
URL url = new URL(linkUrl);
HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();
httpURLConnect.setConnectTimeout(3000);
httpURLConnect.connect();
if(httpURLConnect.getResponseCode()==200)
{
System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage());
}
if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND)
{
System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage() + " - "+ HttpURLConnection.HTTP_NOT_FOUND);
}catch(Exception e){}}}
************************------------------*****************
90- How to read write excel files using Apache POI.
Ans: Basics of APACHE POI
There are two main prefixes which you will encounter when working with Apache POI:
· HSSF: denotes the API is for working with Excel 2003 and earlier.
· XSSF: denotes the API is for working with Excel 2007 and later.
And to get started the Apache POI API, you just need to understand and use the following 4 interfaces:
· Workbook: high level representation of an Excel workbook. Concrete implementations are: HSSFWorkbook andXSSFWorkbook.
· Sheet: high level representation of an Excel worksheet. Typical implementing classes are HSSFSheet and XSSFSheet.
· Row: high level representation of a row in a spreadsheet. HSSFRow and XSSFRow are two concrete classes.
· Cell: high level representation of a cell in a row. HSSFCell and XSSFCell are the typical implementing classes.
Now, let’s walk through some real-life examples.
Reading from Excel File Examples
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out =
new FileOutputStream(new File("C:\\test.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Create new Excel File
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//..
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
//Create a new row in current sheet
Row row = sheet.createRow(0);
//Create a new cell in current row
Cell cell = row.createCell(0);
//Set value to new value
cell.setCellValue("Blahblah");
Write data into the Excel File
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
Map<String, Object[]> data = new HashMap<String, Object[]>();
data.put("1", new Object[] {"Emp No.", "Name", "Salary"});
data.put("2", new Object[] {1d, "John", 1500000d});
data.put("3", new Object[] {2d, "Sam", 800000d});
data.put("4", new Object[] {3d, "Dean", 700000d});
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof Date)
cell.setCellValue((Date)obj);
else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
}
}
try {
FileOutputStream out =
new FileOutputStream(new File("C:\\new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
************************------------------*****************
91- Have you ever done connection with Database using JDBC?
Ans-Yes.Used MySQL as database.
************************------------------*****************
92- Read CSV files.
Ans-Program to read csv file.
package blog;
import java.io.FileReader;
import java.util.Iterator;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
public class ReadCsvFiles {
public static void main(String[] args) throws Exception {
// This will load csv file
CSVReader reader = new CSVReader(new FileReader("C:\\Users\\mukesh_otwani\\Desktop\\demo.csv"));
// this will load content into list
List<String[]> li=reader.readAll();
System.out.println("Total rows which we have is "+li.size());
// create Iterator reference
Iterator<String[]>i1= li.iterator();
// Iterate all values
while(i1.hasNext()){
String[] str=i1.next();
System.out.print(" Values are ");
for(int i=0;i<str.length;i++)
{
System.out.print(" "+str[i]);
}
System.out.println(" ");
}
}
}
************************------------------*****************
93- How to read properties files in Selenium?
Ans- Program for reading properties file.
public class ReadFileData {
public static void main(String[] args) {
File file = new File("D:/Dev/ReadData/src/datafile.properties");
FileInputStream fileInput = null; try
{
fileInput = new FileInputStream(file);
} catch (FileNotFoundException e) { e.printStackTrace(); }
Properties prop = new Properties(); //load properties file try
{
prop.load(fileInput);
} catch (IOException e) { e.printStackTrace(); }
WebDriver driver = new FirefoxDriver();
driver.get(prop.getProperty("URL")); driver.findElement(By.id("Email")).sendKeys(prop.getProperty("username")); driver.findElement(By.id("Passwd")).sendKeys(prop.getProperty("password")); driver.findElement(By.id("SignIn")).click();
System.out.println("URL ::" + prop.getProperty("URL")); System.out.println("User name::" +prop.getProperty("username"));
System.out.println("Password::" +prop.getProperty("password"));
} }
The below is the Output after executing the program: We are passing the properties values to the webdriver and printing the values at end
URL::http://gmail.com
Username::testuser
Password::password123
************************------------------*****************
94- Does Selenium support mobile automation?
Ans-using Appium or other automation tool (need to confirm more on it.)
************************------------------*****************
95- What is Selendroid?
Ans-Selendroid can be used to test already built apps. Those Android apps (apk file) must exist on the machine, where theselendroid-standalone server will be started. The reason for this is that a customized selendroid-server for the app under test (AUT) will be created. Both apps (selendroid-server and AUT) must be signed with the same certificate in order to install the apks on the device.
************************------------------*****************
96- What is Appium?
Ans- Appium aims to automate any mobile app from any language and any test framework, with full access to back-end APIs and DBs from test code. Write tests with your favorite dev tools using all the above programming languages, and probably more (with the Selenium WebDriver API and language-specific client libraries).
************************------------------*****************
97- What is same origin policy in Selenium?
Ans-First of all “Same Origin Policy” is introduced for security reason, and it ensures that content of your site will never be accessible by a script from another site. As per the policy, any code loaded within the browser can only operate within that website’s domain.
Same Origin policy prohibits JavaScript code from accessing elements from a domain that is different from where it was launched. Example, the HTML code in www.google.com uses a JavaScript program "testScript.js". The same origin policy will only allow testScript.js to access pages withingoogle.com such as google.com/mail, google.com/login, or google.com/signup. However, it cannot access pages from different sites such as yahoo.com/search or fbk.com because they belong to different domains.
To avoid “Same Origin Policy” proxy injection method is used, in proxy injection mode the Selenium Server acts as a client configured HTTP proxy , which sits between the browser and application under test and then masks the AUT under a fictional URL
Selenium uses java script to drives tests on a browser; Selenium injects its own js to the response which is returned from aut. But there is a java script security restriction (same origin policy) which lets you modify html of page using js only if js also originates from the same domain as html. This security restriction is of utmost important but spoils the working of Selenium. This is where Selenium server comes to play an important role.
************************------------------*****************
98- What is Selenium grid, hub, node and commands that used in Selenium Grid?
Ans- Selenium Grid:Selenium Grid is a tool that distributes the tests across multiple physical or virtual machines so that we can execute scripts in parallel (simultaneously). It dramatically accelerates the testing process across browsers and across platforms by giving us quick and accurate feedback.
Hub: The hub can also be understood as a server which acts as the central point where the tests would be triggered. A Selenium Grid has only one Hub and it is launched on a single machine once.
Node: Nodes are the Selenium instances that are attached to the Hub which execute the tests. There can be one or more nodes in a grid which can be of any OS and can contain any of the Selenium supported browsers.
************************------------------*****************
99-What is the difference between / and // in XPATH?Ans- “/” It’s starts search selection from root element in document. (absolute path)
“//” It start selection from anywhere in XML document. (relative path)
************************------------------*****************
100- Can we automate Flash application in Selenium?
Ans-The straightforward answer to it is that Selenium has no interface to interact with your Flash content. Flash files are programmed in ActionScript and are very similar to JavaScript. Flash files also contains programming Elements just like other languages. For e.g. they too have buttons, text box etc. Interacting with these elements cause the Flash file to call some internal methods to do the task.
It’s a fairly simple process. All you have to do is use the ExternalInterface class. We will start it with a small example. This is a small flash application which contains 3 buttons. Add, Subtract and Multiply. These three buttons when clicked sends a text to a Text control and write down what the name of the button is. So if you click Add you will find text “Add” being added to the Text control.************************------------------*****************
Thanks
Hey all I just wanted to say thanks! I have been a reader for several montha. I regularly refer to articles from this blog when discussing or advising colleagues about testing / engineering best practises.
ReplyDeleteSelenium Training Course
Thanks for posting such a great article.you done a great job selenium Online Training
ReplyDeleteHi,I have been trading in stocks using Flattrade and I am really happy with the experience. They charge a flat free of ₹10 for trading and Zero brokerage on all equity delivery. More importantly, Flattrade gives you a stable trading experience on its advanced Mobile, web and windows platforms. Use the below link to open FREE demat account.https://flattrade.in/ and investing in IPO is totally free https://flattrade.in/kosh/upcoming-ipos-2021
ReplyDelete