Tuesday, 5 January 2016

Selenium Interview Questions.

Ques 1) What are the annotations used in TestNG ?
Ans: @Test, @BeforeSuite, @AfterSuite, @BeforeTest, @AfterTest, @BeforeClass, @AfterClass, @BeforeMethod, @AfterMethod.
Ques 2) How do you read data from excel ?
                FileInputStream fis = new FileInputStream(“path of excel file”);
                 Workbook wb = WorkbookFactory.create(fis); 
                Sheet s = wb.getSheet(“sheetName”); 
             String value = s.getRow(rowNum).getCell(cellNum).getStringCellValue();
Ques 3) What is the use of xpath ?
Ans- it is used to find the WebElement in web page. It is very useful to identify the dynamic web elements.
Ques 4) What are different types of locators ?
Ans- There are 8 types of locators and all are the static methods of the By class.
By.id(), By.name(), By.tagName(), By.className(), By.linkText(), By.partialLinkText(), By.xpath, By.cssSelector().
Ques 5) What is the difference between Assert and Verify?
Ans- Assert- it is used to verify the result. If the test case fail then it will stop the execution of the test case there itself and move the control to other test case.
Verify- it is also used to verify the result. If the test case fail then it will not stop the execution of that test case.
Ques 6) What is the alternate way to click on login button?
Ans- use submit() method but it can be used only when attribute type=submit.
Ques 7) How do you verify if the checkbox/radio is checked or not ?
Ans- We can use isSelected() method.
Syntax –
         driver.findElement(By.xpath("xpath of the checkbox/radio button")).isSelected();
If the return value of this method is true then it is checked else it is not.
Ques 8) How do you handle alert pop-up ?
Ans- To handle alert pop-ups, we need to 1st switch control to alert pop-ups then click on ok or cancle then move control back to main page.
Syntax-
String mainPage = driver.getWindowHandle();
 Alert alt = driver.switchTo().alert(); // to move control to alert popup
 alt.accept(); // to click on ok.
 alt.dismiss(); // to click on cancel.
 //Then move the control back to main web page-
 driver.switchTo().window(mainPage); → to switch back to main page.
Ques 9) How do you launch IE/chrome browser?
Ans- Before launching IE or Chrome browser we need to set the System property.
//To open IE browser
 System.setProperty(“webdriver.ie.driver”,”path of the iedriver.exe file ”);
 WebDriver driver = new InternetExplorerDriver();
//To open Chrome browser → System.setProperty(“webdriver.chrome.driver”,”path of the chromeDriver.exe file ”);
 WebDriver driver = new ChromeDriver();
Ques 10) How to perform right click using WebDriver?
Ans- Use Actions class
Actions act = new Actions(driver); // where driver is WebDriver type
 act.moveToElement(webElement).perform();
 act.contextClick().perform();
Ques 11) How do perform drag and drop using WebDriver?
Ans- Use Action class
Actions act = new Actions(driver);
 WebElement source = driver.findElement(By.xpath(“ -----”)); //source ele which you want to drag
 WebElement target = driver.findElement(By.xpath(“ -----”)); //target where you want to drop
 act.dragAndDrop(source,target).perform();
Ques 12) Give the example for method overload in WebDriver.
Ans- frame(string), frame(int), frame(WebElement).
Ques 13) How do you upload a file?
Ans- To upload a file we can use sendKeys() method.
        driver.findElement(By.xpath(“input field”)).sendKeys(“path of the file which u want to upload”);
Ques 14) How do you click on a menu item in a drop down menu?
Ans- If that menu has been created by using select tag then we can use the methods selectByValue() or selectByIndex() or selectByVisibleText(). These are the methods of the Select class.
If the menu has not been created by using the select tag then we can simply find the xpath of that element and click on that to select.
Ques 15) How do you simulate browser back and forward ?
driver.navigate().back();
 driver.navigate().forward();
Ques 16) How do you get the current page URL ?
                            driver.getCurrentUrl();
Ques 17) What is the difference between ‘/’ and ‘//’ ?
Ans- //- it is used to search in the entire structure.
/- it is used to identify the immediate child.
Ques 18) What is the difference between findElement and findElements?
Ans- Both methods are abstract method of WebDriver interface and used to find the WebElement in a web page.
findElement() – it used to find the one web element. It return only one WebElement type.
findElements()- it used to find more than one web element. It return List of WebElements.
Ques 19) How do you achieve synchronization in WebDriver ?
Ans- We can use implicit wait.
Syntax- driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
Here it will wait for 10sec if while execution driver did not find the element in the page immediately. This code will attach with each and every line of the script automatically. It is not required to write every time. Just write it once after opening the browser.
Ques 20) Write the code for Reading and Writing to Excel through Selenium ?
FileInputStream fis = new FileInputStream(“path of excel file”);
 Workbook wb = WorkbookFactory.create(fis);
 Sheet s = wb.getSheet("sheetName");
 String value = s.getRow(rowNum).getCell(cellNum).getStringCellValue(); // read data
 s.getRow(rowNum).getCell(cellNum).setCellValue("value to be set"); //write data
 FileOutputStream fos = new FileOutputStream(“path of file”);
 wb.write(fos); //save file
Ques 21) How to get typed text from a textbox ?
Ans- use getAttribute(“value”) method by passing arg as value.
String typedText = driver.findElement(By.xpath("xpath of box")).getAttribute("value"));
Ques 22) What are the different exceptions you got when working with WebDriver ?
Ans- ElementNotVisibleException, ElementNotSelectableException, NoAlertPresentException, NoSuchAttributeException, NoSuchWindowException, TimeoutException, WebDriverException etc.
Ques 23) What are the languages supported by WebDriver ?
Ans- Python, Ruby, C# and Java are all supported directly by the development team. There are also webdriver implementations for PHP and Perl.
Ques 24) How do you clear the contents of a textbox in selenium ?
Ans- Use clear() method.
driver.findElement(By.xpath("xpath of box")).clear();
Ques 25) What is a Framework ?
Ans- A framework is set of automation guidelines which help in
Maintaining consistency of Testing, Improves test structuring, Minimum usage of code, Less Maintenance of code, Improve re-usability, Non Technical testers can be involved in code, Training period of using the tool can be reduced, Involves Data wherever appropriate.
There are five types of framework used in software automation testing:
1-Data Driven Automation Framework
2-Method Driven Automation Framework
3-Modular Automation Framework
4-Keyword Driven Automation Framework
5-Hybrid Automation Framework , its basically combination of different frameworks. (1+2+3).
Ques 26) What are the prerequisites to run selenium webdriver?
Ans- JDK, Eclipse, WebDriver(selenium standalone jar file), browser, application to be tested.
Ques 27) What are the advantages of selenium webdriver?
Ans- a) It supports with most of the browsers like Firefox, IE, Chrome, Safari, Opera etc.
b) It supports with most of the language like Java, Python, Ruby, C# etc.
b) Doesn’t require to start server before executing the test script.
c) It has actual core API which has binding in a range of languages.
d) It supports of moving mouse cursors.
e) It support to test iphone/Android applications.
Ques 28) What is WebDriverBackedSelenium ?
Ans- WebDriverBackedSelenium is a kind of class name where we can create an object for it as below
Selenium wbdriver= new WebDriverBackedSelenium(WebDriver object name, "URL path of website")
The main use of this is when we want to write code using both WebDriver and Selenium RC , we must use above created object to use selenium commands.
Ques 29) How to invoke an application in webdriver ?
driver.get(“url”); or driver.navigate().to(“url”);
Ques 30) What is Selenium Grid ?
Ans- Selenium-Grid allows you to run your tests on different machines against different browsers in parallel. That is, running multiple tests at the same time against different machines, different browsers and operating systems. Essentially, Selenium-Grid support distributed test execution. It allows for running your tests in a distributed test execution environment.
Ques 31) How to get the number of frames on a page ?
List <WebElement> framesList = driver.findElements(By.xpath("//iframe"));
 int numOfFrames = frameList.size();
Ques 32) How do you simulate scroll down action ?
Ans- Use java script to scroll down-
JavascriptExecutor jsx = (JavascriptExecutor)driver;
 jsx.executeScript("window.scrollBy(0,4500)", ""); //scroll down, value 4500 you can change as per your req
 jsx.executeScript("window.scrollBy(450,0)", ""); //scroll up
 ex-
 public class ScrollDown {
 public static void main(String[] args) throws InterruptedException {
 WebDriver driver = new FirefoxDriver();
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 driver.get("http://www.flipkart.com/womens-clothing/pr?sid=2oq,c1r&otracker=hp_nmenu_sub_women_1_View%20all");
 driver.manage().window().maximize();
 JavascriptExecutor jsx = (JavascriptExecutor)driver;
 jsx.executeScript("window.scrollBy(0,4500)", ""); //scroll down
 Thread.sleep(3000);
 jsx.executeScript("window.scrollBy(450,0)", ""); //scroll up
 }
 }
Ques 33) What is the command line we have to write inside a .bat file to execute a selenium project when we are using testng ?
Ans- java -cp bin;jars/* org.testng.TestNG testng.xml
Ques 34) Which is the package which is to be imported while working with WebDriver ?
Ans- org.openqa.selenium
Ques 35) How to check if an element is visible on the web page ?
Ans- use isDisplayed() method. The return type of the method is boolean. So if it return true then element is visible else not visible.
            driver.findElement(By.xpath("xpath of elemnt")).isDisplayed();
Ques 36) How to check if a button is enabled on the page ?
Ans- Use isEnabled() method. The return type of the method is boolean. So if it return true then button is enabled else not enabled.
            driver.findElement(By.xpath("xpath of button")).isEnabled();
Ques 37) How to check if a text is highlighted on the page ?
Ans- To identify weather color for a field is different or not-
String color = driver.findElement(By.xpath("//a[text()='Shop']")).getCssValue("color");
 String backcolor = driver.findElement(By.xpath("//a[text()='Shop']")).getCssValue("background-color");
 System.out.println(color);
 System.out.println(backcolor);
Here if both color and back color different then that means that element is in different color.
Ques 38) How to check the checkbox or radio button is selected ?
Ans- Use isSelected() method to identify. The return type of the method is boolean. So if it return true then button is selected else not enabled.
            driver.findElement(By.xpath("xpath of button")).isSelected();
Ques 39) How to get the title of the page ?
Ans- Use getTitle() method.
Syntax- driver.getTitle();
Ques 40) How do u get the width of the textbox ?
driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getWidth();
 driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getHeight();
Ques 41) How do u get the attribute of the web element ?
Ans- driver.getElement(By.tagName(“img”)).getAttribute(“src”) will give you the src attribute of this tag. Similarly, you can get the values of attributes such as title, alt etc.
Similarly you can get CSS properties of any tag by using getCssValue(“some propety name”).
Ques 42) How to check whether a text is underlined or not ?
Ans- Identify by getCssValue(“border-bottom”) or sometime getCssValue(“text-decoration”) method if the
 cssValue is 'underline' for that WebElement or not.
 ex- This is for when moving cursor over element that is going to be underlined or not-
 public class UnderLine {
 public static void main(String[] args) {
 WebDriver driver = new FirefoxDriver();
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 driver.get("https://www.google.co.in/?gfe_rd=ctrl&ei=bXAwU8jYN4W6iAf8zIDgDA&gws_rd=cr");
 String cssValue= driver.findElement(By.xpath("//a[text()='Hindi']")).getCssValue("text-decoration");
 System.out.println("value"+cssValue);
 Actions act = new Actions(driver);
 act.moveToElement(driver.findElement(By.xpath("//a[text()='Hindi']"))).perform();
 String cssValue1= driver.findElement(By.xpath("//a[text()='Hindi']")).getCssValue("text-decoration");
 System.out.println("value over"+cssValue1);
 driver.close();
 } 
}
Ques 43) How to change the URL on a webpage using selenium web driver ?
driver.get(“url1”);
 driver.get(“url2”);
Ques 44) How to hover the mouse on an element ?
Actions act = new Actions(driver);
 act.moveToElement(webelement); //webelement on which you want to move cursor
Ques 45) What is the use of getOptions() method ?
Ans- getOptions() is used to get the selected option from the dropdown list.
Ques 46) What is the use of deSelectAll() method ?
Ans- It is used to deselect all the options which have been selected from the dropdown list.
Ques 47) Is WebElement an interface or a class ?
Ans- WebDriver is an Interface.
Ques 48) FirefoxDriver is class or an interface and from where is it inherited ?
Ans- FirefoxDriver is a class. It implements all the methods of WebDriver interface.
Ques 49) Which is the super interface of webdriver ?
Ans- SearchContext.
Ques 50) What is the difference b/w close() and quit()?
Ans- close() – it will close the browser where the control is.
quit() – it will close all the browsers opened by WebDriver.
Ques 1) Can we enter text without using sendKeys() ?
Ans – Yes we can enter text without using sendKeys() method. We have to use combination of javascript and wrapper classes with WebDriver extension class, check the below code-
public static void setAttribute(WebElement element, String attributeName, String value)
    {
         WrapsDriver wrappedElement = (WrapsDriver) element;
         JavascriptExecutor driver = (JavascriptExecutor)wrappedElement.getWrappedDriver();
         driver.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])", element, attributeName, value);
     }
call the above method in the test script and pass the text field attribute and pass the text you want to enter.
Ques 2) There is a scenario whenever “Assert.assertEquals()” function fails automatically it has to take screenshot. How can you achieve this ?
Ans- By using EventFiringWebDriver.
Syntax-EventFiringWebDriver eDriver=new EventFiringWebDriver(driver);
File srcFile = eDriver.getScreenshotAs(OutputType.FILE);
 FileUtils.copyFile(srcFile, new File(imgPath));
Ques 3) How do you handle https website in selenium ?
Ans- By changing the setting of FirefoxProfile.
Syntax-public class HTTPSSecuredConnection {
 public static void main(String[] args){
 FirefoxProfile profile = new FirefoxProfile();
 profile.setAcceptUntrustedCertificates(false);
 WebDriver driver = new FirefoxDriver(profile);
 driver.get("url");
 }
 }
Ques 4) How to login into any site if its showing any authetication popup for user name and pass ?
Ans – pass the username and password with url.
Syntax- http://username:password@url
 ex- http://creyate:jamesbond007@alpha.creyate.com
Ques 5) What is the name of Headless browser.
Ans- HtmlUnitDriver.
Ques 6) Open a browser in memory means whenever it will try to open a browser the browser page must not come and can perform the operation internally.
Ans- use HtmlUnitDriver.
ex-
public class Memory {
 public static void main(String[] args) {
 HtmlUnitDriver driver = new HtmlUnitDriver(true);
 driver.setJavascriptEnabled(false);
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 driver.get("https://www.google.co.in/");
 System.out.println(driver.getTitle());
 }
 }
Ques 7) What are the benefits of using TestNG ?
Ans-
a) TestNG allows us to execute of test cases based on group.
b) In TestNG Annotations are easy to understand.
c) Parallel execution of Selenium test cases is possible in TestNG.
d) Three kinds of report generated
e) Order of execution can be changed
f) Failed test cases can be executed
g) Without having main function we can execute the test method.
h) An xml file can be generated to execute the entire test suite. In that xml file we can   rearrange our execution order and we can also skip the execution of particular test case.
Ques 8) How do you take screen shot without using EventFiringWebDriver ?
Ans-
File srcFile = ((TakeScreenshot)driver).getScreenshotAs(OutputType.FILE); //now we can do anything with this screenshot
 like copy this to any folder-
 FileUtils.copyFile(srcFile,new File(“folder name where u want to copy/file_name.png”));
Ques 9) How do you send ENTER/TAB keys in WebDriver ?
Ans- use click() or submit() [submit() can be used only when type=’submit’]) method for ENTER. Or use Actions class to press keys.
For Enter-
                       act.sendKeys(Keys.RETURN);
For Tab-
                        act.sendKeys(Keys.ENTER);
where act is Actions class type. ( Actions act = new Actions(driver); )
Ques 10) What is Datadriven framework & Keyword Driven ?
Ans- Datadriven framework- In this Framework , while Test case logic resides in Test Scripts, the Test Data is separated and kept outside the Test Scripts.Test Data is read from the external files (Excel File) and are loaded into the variables inside the Test Script. Variables are used both for Input values and for Verification values.
Keyword Driven framework- The Keyword-Driven or Table-Driven framework requires the development of data tables and keywords, independent of the test automation tool used to execute them . Tests can be designed with or without the Application. In a keyword-driven test, the functionality of the application-under-test is documented in a table as well as in step-by-step instructions for each test.
Ques 11) While explaining the framework, what are points which should be covered ?
Ans-
a) What is the frame work.
b) Which frame work you are using.
c) Why This Frame work.
d) Architecture.
e) Explanation of every component of frame work.
f) Process followed in frame work.
g) How & when u execute the frame work.
h) Code (u must write code and explain).
i) Result and reporting .
j) You should be able to explain it for 20 Minutes.
Ques 12) How to switch back from a frame ?
Ans- use method defaultContent().
                Syntax – driver.switchTo().defaultContent();
Ques 13) How to type text in a new line inside a text area ?
Ans- Use \n for new line.
            ex- webelement.sendKeys(“Sanjay_Line1.\n Sanjay_Line2.”);
it will type in text box as-
Sanjay_Line1.
Sanjay_Line2.
Ques 14) What is the use of AutoIt tool ?
Ans- Some times while doing testing with selenium, we get stuck by some interruptions like a window based pop up. But selenium fails to handle this as it has support for only web based application. To overcome this problem we need to use AutoIT along with selenium script. AutoIT is a third party tool to handle window based applications. The scripting language used is in VBScript.
Ques 15) How to perform double click using WebDriver ?
Ans- use doubleClick() method.
Syntax- Actions act = new Actions(driver);
 act.doubleClick(webelement);
Ques 16) How to press Shift+Tab ?
Ans-
String press = Keys.chord(Keys.SHIFT,Keys.ENTER);
 webelement.sendKeys(press);
Ques 17) What is the use of contextClick() ?
Ans- It is used to right click.
Ques 18) What is the difference b/w getWindowHandles() and getWindowHandle() ?
Ans- getWindowHandles()- is used to get the address of all the open browser and its return type is Iterator<String>.
getWindowHandle()- is used to get the address of the current browser where the conrol is and return type is String.
Ques 19) How do you accommodate project specific methods in your framework ?
Ans- 1st go through all the manual test cases and identify the steps which are repeating. Note down such steps and make them as methods and write into ProjectSpecificLibrary.
Ques 20) What are different components of your framework ?
Ans- Library- Assertion, ConfigLibrary, GenericLibrary, ProjectSpecificLibrary, Modules.
Drivers folder, Jars folder, excel file.
Ques 21) What are the browsers supported by Selenium IDE ?
Ans- Mozilla FireFox only. Its an Firefox add on.
Ques 22) What are the limitations of Selenium IDE ?
Ans-
a) It does not supports looping or conditional statements. Tester has to use native languages to write logic in the test case.
b) It does not supports test reporting, you have to use selenium RC with some external reporting plugin like TestNG or JUint to get test execution report.
c) Error handling is also not supported depending on the native language for this.
d) Only support in Mozilla FireFox only. Its an Firefox add on.
Ques 23) How to check all checkboxes in a page ?
Ans-
List&lt;webElement&gt; chkBox = driver.findElements(By.xpath(“//htmltag[@attbute='checkbox']”));
 for(int i=0; i&lt;=chkBox.size(); i++){
 chkBox.get(i).click();
 }
Ques 24) Count the number of links in a page.
Ans- use the locator By.tagName and find the elements for the tag //a then use loop to count the number of elements found.
Syntax- int count = 0;
 List&lt;webElement&gt; link = driver.findElements(By.tagName(“a”));
 System.out.println(link.size()); // this will print the number of links in a page.
Ques 25) How do you identify the Xpath of element on your browser ?
And- to find the xpath , we use Firebug addons on firefox browser and to identify the xpath written we use Firepath addons.
Syntax- //htmltag[@attname='attvalue'] or //html[text()='textvalue'] or //htmltag[contains(text(),'textvalue')] or //htmltag[contains(@attname,'attvalue')]
Ques 26) What is Selenium Webdriver ?
Ans- WebDriver is the name of the key interface against which tests should be written in Java. All the methods of WebDriver have been implementated by RemoteWebDriver.
Ques 27) What is Selenium IDE ?
Ans- Selenium IDE is a complete integrated development environment (IDE) for Selenium tests. It is implemented as a Firefox Add-On, and allows recording, editing, and debugging tests. It was previously known as Selenium Recorder.
Scripts may be automatically recorded and edited manually providing autocompletion support and the ability to move commands around quickly.
Scripts are recorded in Selenese, a special test scripting language for Selenium. Selenese provides commands for performing actions in a browser (click a link, select an option), and for retrieving data from the resulting pages.
Ques 28) What are the flavors of selenium ?
Ans- selenium IDE, selenium RC, Selenium WebDriver and Selenium Grid.
Ques 29) What is selenium ?
Ans- Its an open source Web Automation Tool. It supports all types of web browsers. Despite being open source its actively developed and supported.
Ques 30) Advantages of selenium over other tools ?
Ans-
a) Its free of cost,
b) it supports many languages like Java, C#, Ruby, Python etc.,
c) it allows simple and powerful DOM-level testing etc.
Ques 31) What is main difference between RC and webdriver ?
Ans- Selenium RC injects javascript function into browsers when the web page is loaded.
Selenium WebDriver drives the browser using browser’s built-in support.
Ques 32) Why you choose webdriver over RC ?
Ans-
a) Native automation faster and a little less prone to error and browser configuration,
b) Does not Requires Selenium-RC Server to be running
c) Access to headless HTMLUnitDriver can allow really fast tests
d) Great API etc.
Ques 33) Which one is better xpath or CSS ?
Ans- xpath.
Ques 34) How will you handle dynamic elements ?
Ans- By writing relative xpath.
Ques 35) what are the different assertions or check points used in your script ?
Ans- The common types of validations are:
a) Is the page title as expected,
b) Validations against an element on the page,
c) Does text exist on the page,
d) Does a javascript call return an expected value.
method used for validation – Assert.assertEquals();
Ques 36) What is actions class in WebDriver ?
Ans- Actions class is used to control the actions of mouse.
Ques 37) What is the difference between @BeforeMethod and @BeforeClass ?
Ans- @BeforeMethod- this will execute before every @Test method.
@BeforeClass- this will execute before every class.
Ques 38) What are the different attributes for @Test annotation ?
Ans- alwaysRun, dataProvider, dependsOnMethods, enabled, expectedExceptions, timeOut etc.
ex- @Test(expectedExceptions = ArithmeticException.class)
 @Test(timeOut = 2000)
Ques 39) Can we run group of test cases using TestNG ?
Ans- yes.
Ques 40) What is object repository ?
Ans- An object repository is a very essential entity in any UI automation tool. A repository allows a tester to store all the objects that will be used in the scripts in one or more centralized locations rather than letting them be scattered all over the test scripts. The concept of an object repository is not tied to WET alone. It can be used for any UI test automation. In fact, the original reason why the concept of object repositories were introduced was for a framework required by QTP.
Ques 41) What are oops concepts ?
Ans-
a) Encapsulation,
b) Abstraction,
c) Polymorphism,
d) Inheritance.
Ques 42) What is inheritance ?
Ans- Inherit the feature of any class by making some relations between the class/interface is known as inheritance.
Ques 43) What is difference between overload and override ?
Ans- The methods by passing different arguments list/type is known as overloading of methods while having the same method signature with different method body is known as method overriding.
Ques 44) Does java supports multiple inheritance ?
Ans- Interface supports multiple inheritance but class does not support.
Ques 45) Write a java program for swapping of two numbers ?
Ans-
public class Swapping{
 public static void main(String[] args){
 Scanner in = new Scanner(System.in);
 System.out.println(“enter the 1st num”);
 int a = in.nextInt();
 System.out.println(“enter the 2nd num”);
 int b = in.nextInt();
 System.out.println(“before swapping a=”+a+” and b= ”+b);
 int x = a;
 a = b;
 b = x;
 System.out.println(“After swapping a=”+a+” and b= ”+b);
 }
 }
Ques 46) Write a java program for factorial of a given number.
Ans-
public class Factorial{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.println(“enter the num for which u want the factorial”);
int num = in.nextInt();
for(int i=num-1; i&gt;0; i-- ){
num = num*i;
}
System.out.println(num);
}   }
Ques 47) What are the different access specifiers in Java?
Ans- private, default, protected and public.
Ques 48) Why do we go for automation testing ?
Ans- Reasons-
a) Manual testing of all work flows, all fields, all negative scenarios is time and cost consuming.
b) It is difficult to test for multi lingual sites manually.
c) Automation does not require human intervention. We can run automated test unattended(Overnight).
d) Automation increases speed of test execution.
e) Automation helps increase test coverage.
f) Manual testing can become boring and hence error prone.
Ques 49) What is testing strategy ?
Ans- A Test Strategy document is a high level document and normally developed by project manager. This document defines “Software Testing Approach” to achieve testing objectives. The Test Strategy is normally derived from the Business Requirement Specification document.
Ques 50) ) write a code to make use of assert if my username is incorrect.
try{

Assert.assertEquals(expUserName, actUserName);

}catch(Exception e){

Syste.out.println(name is invalid);

}


TestNG Eclipse Plugin Installation - Offline



TestNG is good framework inspired by JUnit, It is having advanced features than JUnit. I tried to install TestNG eclipse plugin to my Eclipse version of Juno. But I got some hell errors. Finally I was failed to install that in online. Then I tried to install that in offline. Initially I did some research on how to install TestNG plugin in offline and I found different jars for different versions of eclipse and some online forum users stated that they still getting some configuration issues. Then I decided to build suitable version of TestNG plugin with my own Eclipse. Follow the below procedure for successful installation

Download TestNG Eclipse Plugin Project

Download TestNG from the Github ( https://github.com/cbeust/testng-eclipse ). Once you download the ZIP file, extract it. Now you can see testing-eclipse-plugin folder in it. This is the Eclipse plugin project that we have to build.

Import Eclipse Plugin Project

Open your Eclipse
Click on "File > Import"
Now select "General > Existing Projects into Workspace"
Now click on "Next"
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEga94J2iM5q_7UPejxAP18_f0Jop-thXqeyhLabTeF_wlN8gv4pCpxlbxx5Jhow5LdznKHNF6a3_tWq4CUHStgSQcGn6yxcoVbttT8HPWEKpBIXS7EFE1YIrVlmqNCooVtOG1vkvlJSGck/s512/eclipse-testng-1.jpg
Now click on "Browse"
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgShyphenhyphensP4VS99-R8obkDOywNLeG3hpp-LQF4lLp6rEL0dqQYOFsBWb4DVpIhyphenhyphen4bMg1yIWlhpXR3v1lIqZBcwmzRs0VaeUqdHBRIXumqwmyLyCBZ8nfYT1GdcmyRBK5Lsrav76YuVwGVQ5cU/s522/eclipse-testng-2.jpg
Now select the folder "testing-eclipse-plugin"
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQ9WWKVhlBHjkjFYWc8kojN6mQ0O9U75PuToyqEOQFwN8Uf4bR_XMqOP2wuvBP1ejF37FB0JgTUhW37-Vy0HQJ88Y3a7NB9Otl5be6DupIHcDVN2UAhW2CxqN1FSsZyYXHt2uw56aWW28/s512/eclipse-testng-3.jpg
Now click on "ok"
Project will be created
Now right click on the project and click on "export"
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjvonfwCyhxJ-mSv25XQuMbDg2FL76TEknGMeAc0nNIwyI-CHhTl5rmp2cbahnIBsVET2qJMZjO9z0ObAefBttXVqrDHcO5mDS-w_5cfTwReXOTvk3PU3hTPmrJaCCOrLv4hcIuLQFRBp0/s441/eclipse-testng-4.jpg
Now select "Plug-in Development > Deployable plug-ins and fragments"
Click on "Next"
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgUsWOohgvuuaJfmCFM92G60ryftaz6pjaE4rhEF-nUofHYybC2GhQ4dfb-FlsyiVd4-Gldul4NsGp__hdTH5i0YDpXoxXEGjhWJ74469Feh9FGcCIylSzHkLls_xVnciacdNoyj1Vykhg/s628/eclipse-testng-5.jpg
Now click on "Browse" and select the target folder
Click on "Finish"
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTKH0r7iSj4MEEPyAofrfQYBtUBPjXcxQWd_gkM98MFENLEzFRlujOjQJnJA8YmRFmIIlAHdmCTWV_kEt9Ih26bHa1rOl5gv0es59Mri5eNOuk7hdC0oNZunwRH-lW5kXFEKcMW6ucoD8/s512/eclipse-testng-6.jpg
Jar will be generated as like shown in the below image
This is the plugin jar which we required
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3FHKJV-V9ScDSZm50kS4_cnCF5BaioRwrcnGY2ZahX_jfIkGfX76CkixlAPit6ZHo7YPKWQ8lJjMHvsv3ZAiGm-GkFxBX0MoqSybUH8JPLbwSmFDGl6lLy0iUJQwv-NuP0cPYEtpIRXg/s788/eclipse-testng-7.jpg
Now copy this jar and paste in "dropins" folder of eclipse
Now restart the eclipse, Now you can see all TestNG options in active mode


Sunday, 22 November 2015

Executing Failed TestCases in Selenium using TestNG

Scenario:-

We want to re-run only the failed testcases in selenium, rather than running the entire suite.

Approach:-
Every time tests fail in a suite, TestNG creates a file called testng-failed.xml in the output directory. This XML file contains the necessary information to rerun only these methods that failed, utlizing this we can easily rerun the failed tests without having to run the entire test suite.

Note:- For running the test exactly after the failure we need to call the method that failed. We can get that method name from  IRetryAnalyzer interface . If we just want to rerun all the failed test cases together, then we can give the testng-failed.xml as input xml after the first execution.But remember this will result in creation of 2 reports, one of previous run + latest run of the failed test cases, rather than having the consolidated report

Solution:-
Locate the testng-failed.xml file
Project->test-output->testng-failed.xml


Rerun this file to execute only the failed test cases.
(Open file -> CTRL+F11)


Monday, 7 April 2014

Agile Model - SCRUM Process Overview

Lot of testers have interest to know about,
1. What is agile model?
2. What is the advantage of it over other models?

Agile - Simply we can say "On demand, more monitored and controlled testing"
Agile model have benefits like,
1. Easy adoption of requirement changes at any stage.
2. Piece of working product will be arrived very early in life cycle.
3. More monitoring on team so every team members will be in same path and goal.

SCRUM is one of a process of agile methodology. SCRUM involves below terms,
1. Sprint
2. Scrum master
3. User Stories
4. Work Items
5. Sprint Back Logs
6. Sprint retrospective item, etc.

Sprint - Sprint is nothing but the scrum period. i.e. The no of days for between each release like 30 days, 15 days. This is mainly based on customer requirement. If your every sprint consists 30 days, then every 30 days there will be a release. Sometimes release will not be there based on customer request.

Scrum Master - The person responsible to assign the tasks to team members and monitor the team.

User Stories - User Stories are the original requirements from customer. This may be "New functionality" or "Change Request".

Sprint Work Items - Work Items are the Task items created by Scrum Master with Estimated time for each User story. Normally scrum master will create task item for each user story and assign it to some team member with estimated time.

Sprint BackLog Item - Sprint back log items are the sub task items created by every team member for each assigned work item. Team member will create this sprint back log item for each assigned work item and he will set estimated time. This is used to track the daily effort done by team member and to update the status like how much hrs actually worked on this sprint back log item. Automatically this will affect the Work Item related to this Sprint back log item. So finally the User story will be finished by doing all the work items related to that user story.

Sprint Retrospective Item - Retrospective item will be created after sprint release. This should cover the answers for below 2 questions.
1. What went well?
2. What can be Improved?

Now, you should be aware of above terms. Let's see, how actually scrum will be followed in real time projects.
1. Customers will enter the User Stories in your ALM system like TFS, QC, etc.
2. Once received user stories, scrum master will arrange a meeting called Sprint Planning Meeting
3. In Sprint planning meeting, scrum master will discuss with team members like
    What are the user stories we can select for this sprint?,
    Which user story going to handle every team member?, etc.
4. After planning meeting, scrum master will create Sprint Work Items for each user story and assign them to team members. For ex. Login Module is the user story. For this story, scrum master will create work items like Development of Login Module, Testing of Login Module, Regression and Retesting of Login module, etc. and he/she will put the estimated time to finish each work item.
5. Now, team members will pick up their work item and create Sprint Back Log Items i.e. sub work items. For ex. Team member will create sprint back log items like UI development, functionality development, unit testing, etc for Development of Login module work item.
6. Daily team members will work on their tasks and update their actual worked hours (i.e. burning worked hours) against estimated hours in sprint back log items.
7. This will give progress status for every sprint back log item which in-turn update sprint work item's progress. Finally every one can able to know the progress status of each user story.
8. Daily 10 to 15 mins quick meeting will be arranged by scrum master to update daily status, showstoppers and any blockings to continue the planned tasks. Based on this, they will continue their progress. This is called Daliy Scrum Meeting
8. Once everything is OK and working fine and tested, then we will go for release.
9.After the release, scrum master will arrange a meeting called Sprint Retrospective Meeting. In this meeting, every will discuss about the 2 points mentioned above and will create retrospective items if any.
10. In future releases, team members will concentrate to cover the created retrospective items as part of sprint tasks.

Hope this will give you basic idea about the scrum process in agile model...

Sunday, 6 April 2014

Selenium Web Driver Questions & Answers

Question 1:
What is Selenium 2.0? I have heard this buzz word many times.
Answer
Selenium 2.0 is consolidation of two web testing tools – Selenium RC and WebDriver, which claims to give best of both words – Selenium and WebDriver. Selenium 2.0 was officially released only of late.

Question 2:
Why are two tools being combined as Selenium 2.0, what’s the gain?
Answer
Selenium 2.0 promises to give much cleaner API then Selenium RC and at the same time not being restricted by java script Security restriction like same origin policy, which have been haunting Selenium from long. Selenium 2.0 also does not warrant you to use Selenium Server.

Question 3:
So everyone is going to use Selenium 2.0?
Answer
Well no, for example if you are using Selenium Perl client driver than there is no similar offering from Selenium 2.0 and you would have to stick to Selenium 1.0 till there is similar library available for Selenium 2.0

Question 4:
So how do I specify my browser configurations with Selenium 2.0?
Answer
Selenium 2.0 offers following browser/mobile configuration –
·         AndroidDriver,
·         ChromeDriver,
·         EventFiringWebDriver,
·         FirefoxDriver,
·         HtmlUnitDriver,
·         InternetExplorerDriver,
·         IPhoneDriver,
·         IPhoneSimulatorDriver,
·         RemoteWebDriver
And all of them have been implemented from interface WebDriver. To be able to use any of these drivers you need to instantiate their corresponding class.

Question 5:
How is Selenium 2.0 configuration different than Selenium 1.0?
Answer
In case of Selenium 1.0 you need Selenium jar file pertaining to one library for example in case of java you need java client driver and also Selenium server jar file. While with Selenium 2.0 you need language binding (i.e. java, C# etc) and Selenium server jar if you are using Remote Control or Remote WebDriver.

Question 6:
Can you show me one code example of setting Selenium 2.0?
Answer
Here is java example of initializing firefox driver and using Google Search engine –
protected WebDriver webDriver;
//@BeforeClass(alwaysRun=true)
public void startDriver(){
webDriver = new FirefoxDriver();
// Get Google search page and perform search on term “Test”
webDriver.get("http://www.google.com");
webDriver.findElement(By.name("q")).sendKeys("Test");
webDriver.findElement(By.name(“btnG”)).click();

Question 7:
Which web driver implementation is fastest?
Answer
HTMLUnitDriver. Simple reason is HTMLUnitDriver does not execute tests on browser but plain http request – response which is far quick than launching a browser and executing tests. But then you may like to execute tests on a real browser than something running behind the scenes

Question 8:
What all different element locators are available with Selenium 2.0?
Answer
Selenium 2.0 uses same set of locators which are used by Selenium 1.0 – id, name, css, XPath but how Selenium 2.0 accesses them is different. In case of Selenium 1.0 you don’t have to specify a different method  for each locator while in case of Selenium 2.0 there is a different method available to use a different element locator. Selenium 2.0 uses following method to access elements with id, name, css and XPath locator –

driver.findElement(By.id("HTMLid"));
driver.findElement(By.name("HTMLname"));
driver.findElement(By.cssSelector("cssLocator"));
driver.findElement(By.xpath("XPathLocator));

Question 9:
How do I submit a form using Selenium?
Answer
You can use “submit” method on element to submit form –
element.submit();
Alternatively you can use click method on the element which does form submission.

Question 10:
Can I simulate pressing key board keys using Selenium 2.0?
Answer
You can use “sendKeys” command to simulate key board keys as –

element.sendKeys(" and some", Keys.ARROW_UP);
You can also use “sendKeys” to type in text box as –

HTMLelement.sendKeys("testData");

Question 11
How do I clear content of a text box in Selenium 2.0
Answer
You can use “clear” method on text box element to clear its content –
textBoxElement.clear();

Question 12:
How do I select a drop down value using Selenium2.0?
Answer
To select a drop down value, you first need to get the select element using one of element locator and then you can select element using visible text –
Select selectElement = new Select(driver.findElement(By.cssSelector("cssSelector")));
selectElement.selectByVisibleText("India");

Question 13:
What are offering to deal with popup windows while using Selenium 2.0?
Answer
You can use “switchTo” window method to switch to a window using window name. There is also one method “getWindowHandles” which could be used to find all Window handles and subsequently bring control on desired window using window handle –
webDriver.switchTo().window("windowName");
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
}

Question 14:
How about handling frames using Selenium 2.0?
Answer
You can use “switchTo” frame method to bring control on an HTML frame –
driver.switchTo().frame("frameName");
You can also use index number to specify a frame –
driver.switchTo().frame("parentFrame.4.frameName");
This would bring control on frame named – “frameName” of the 4th sub frame names “parentFrame”

Question 15:
Can I navigate back and forth in a browser in Selenium 2.0?
Answer
You can use Navigate interface to go back and forth in a page. Navigate method of WebDriver interface returns instance of Navigation. Navigate interface has methods to move back, forward as well as to refresh a page –
driver.navigate().forward();
driver.navigate().back();
driver.navigate().refresh();

Question 16:
What is the order of fastest browser implementation for WebDriver?
Answer
HTMLUnitDriver is the fastest browser implementation as it does not involves interaction with a browser, This is followed by Firefox driver and then IE driver which is slower than FF driver and runs only on Windows.

 Question 17:
Is it possible to use Selenium RC API with Selenium 2.0?
Answer
You can emulate Selenium 1.0 API with Selenium 2.0 but not all of Selenium 1.0 methods are supported. To achieve this you need to get Selenium instance from WebDriver and use Selenium methods. Method executions might also be slower while simulating Selenium 1.0 with in Selenium 2.0

 Question 18:
Can you show me one example of using Selenium 1.0 in Selenium 2.0?
Answer
Code Sample:
// Create web driver instance
WebDriver driver = new FirefoxDriver();
// App URL
String appUrl = "http://www.google.com";
// Get Selenium instance
Selenium selenium = new WebDriverBackedSelenium(driver, appUrl);
// Tests using selenium
selenium.open(appURL);
selenium.type("name=q""testData");
selenium.click("name=btnG");
// Get back the WebDriver instance
WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getUnderlyingWebDriver();

Question 19:
I had support of lots of browsers while using Selenium 1.0 and it seems lacking with Selenium 2.0, for example how do I use < awesome> browser while using Selenium 2.0?
Answer
There is a class called Capabilities which lets you inject new Capabilities in WebDriver. This class can be used to set testing browser as Safari –
//Instantiate Capabilities
Capabilities capabilities = new DesiredCapabilities()
//Set browser name
capabilities.setBrowserName("this awesome browser");
//Get your browser execution capabilities
CommandExecutor executor = new SeleneseCommandExecutor("http:localhost:4444/""http://www.google.com/", capabilities);
//Setup driver instance with desired Capabilities
WebDriver driver = new RemoteWebDriver(executor, capabilities);

Question 20:
Are there any limitations while injecting capabilities in WebDriver to perform tests on a browser which is not supported by WebDriver?
Answer
Major limitation of injecting Capabilities is that “fundElement” command may not work as expected. This is because WebDriver uses Selenium Core to make “Capability injection” work which is limited by java script security policies.

Question 21:
Can I change User-Agent while using FF browser? I want to execute my tests with a specific User-Agent setting.
Answer
You can create FF profile and add additional Preferences to it. Then this profile could be passed to Firefox driver while creating instance of Firefox –
FirefoxProfile profile = new FirefoxProfile();
profile.addAdditionalPreference("general.useragent.override""User Agent String");
WebDriver driver = new FirefoxDriver(profile);

Question 22:
Is there any difference in XPath implementation in different WebDriver implementations?
Answer
Since not all browsers (like IE) have support for native XPath, WebDriver provides its own implementation for XPath for such browsers. In case of HTMLUnitDriver and IEDriver, html tags and attributes names are considered lower cased while in case of FF driver they are considered case in-sensitive.

Question 23:
My application uses ajax highly and my tests are suffering from time outs while using Selenium 2.0L.
Answer
You can state WebDriver to implicitly wait for presence of Element if they are not available instantly. By default this setting is set to 0. Once set, this value stays till the life span of WebDriver object. Following example would wait for 60 seconds before throwing ElementNotFound exception –
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
WebElement element = driver.findElement(By.id("elementID"));

Question 24:
What if I don’t want to use implicit wait and want to wait only for presence of certain elements?
Answer
You can use explicit wait in this situation to wait for presence of certain element before continuing with test execution. You can use “WebDriverWait” and “ExpectedCondition” to achieve this –

WebDriver driver = new FirefoxDriver();
WebElement myDynamicElement = (new WebDriverWait(driver, 60)).until(new ExpectedCondition<WebElement>(){
@Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("myDynamicElement"));
}});

This is going to wait up to 60 seconds before throwing ElementNotFound exception.

Question 25:
What is RemoteWebDriver? When would I have to use it?
Answer
RemoteWebDriver is needed when you want to use HTMLUnitDriver. Since HTMLUnitDriver runs in memory, you would not see a browser getting launched –
// Create HTMLUnitDriver instance
WebDriver driver = new HtmlUnitDriver();
// Launch Yahoo.com
driver.get("http://www.yahoo.com");

Question 26:
What all languages available to be used with WebDriver?
Answer
Java and C# are on the forefront of WebDriver languages. Support is also available for Python and Ruby. There is also one java script library available for Friefox.

Question 27:
How do I handle java script alert using WebDriver?
Answer
WebDriver would support handling js alerts using Alert interface.
// Bring control on already opened alert
Alert alert = driver.switchTo().alert();
// Get the text of the alert or prompt
alert.getText();
// Click ok on alert
alert.accept();

Question 28:
Could I safely execute multiple instances of WebDriver implementations?
Answer
As far as HTMLUnitDriver and FF drivers are concerned, each instance would be independent of other. In case of IE driver there could be only one instance of IE driver running on Windows. If you want to execute more than one instance of IE driver then you should consider using RemoteWebDriver and virtual machines.

Question 29:
Is it possible to interact with hidden elements using WebDriver?
Answer
Since WebDriver tries to exercise browser as closely as real users would, hence simple answer is No, But you can use java script execution capabilities to interact with hidden elements.

Question 30:
I have all my tests written in Selenium 1.0 (Selenium RC), why should I migrate to Selenium 2.0 (WebDriver)?
Answer
Because –
·         WebDriver has more compact and object oriented API than Selenium 1.0
·         WebDriver simulates user behaviour more closely than Selenium 1.0, for example if a text box is disabled WebDriver would not be able to type text in it while Selenium 1.0 would be
·         WebDriver is supported by Browser vendor themselves i.e. FF, Opera, Chrome etc

Question 31:
My XPath and CSS locators don’t always work with Selenium 2.0, but they used to with Selenium 1.0L.
Answer
In case of XPath, it is because WebDriver uses native browser methods unless it is not available. And this cause complex XPath to be broken. In case of Selenium 1.0 css selectors are implemented using Sizzle Library and not all the capabilities like “contains” are available to be used with Selenium 2.0

Question 32:
How do I execute Java Script in Selenium 2.0?
Answer
You need to use JavaScriptExecutor to execute java script in Selenium 2.0, For example if you want to find tag name of an element using Selenium 2.0 then you can execute java script as following –
WebElement element = driver.findElement(By.id("elementLocator"));
String name = (String) ((JavascriptExecutor) driver).executeScript(
"return arguments[0].tagName", element);

Question 33:
Why does not my java script execution return any value?
Answer
This might happen when you forget to add “return“ keyword while executing java script. Notice the “return” keyword in following statement –
((JavascriptExecutor) driver).executeScript("return window.title;");

Question 34:
Are there any limitations from operating systems while using WebDriver?
Answer
While HTMLUnitDriver, FF Driver and Chrome Driver could be used on all operating systems, IE Driver could be used only with Windows.

Question 35:
Give me architectural overview of WebDriver.
Answer
WebDriver tries to simulate real user interaction as much as possible. This is the reason why WebDriver does not have “fireEvent” method and “getText” returns the text as a real user would see it. WebDriver implementation for a browser is driven by the language which is best to driver it. In case of FF best fit languages are Javascript in an XPCOM component and in IE it is C++ using IE automation. Now the implementation which is available to user is a thin wrapper around the implementation and user need not know about implementation.

Question 36:
What is Remote WebDriver Server?
Answer
Remote WebDriver Server has two components – client and server. Client is WebDriver while Server is java servlet. Once you have downloaded selenium-server-standalone-.jar file you can start it from command line as –
        java -jar selenium-server-standalone-<version-number>.jar

Question 37:
Is there a way to start Remote WebDriver Server from my code?
Answer
First add Remote WebDriver jar in your class path. You also need another server called “Jetty” to use it. You can start sever as following –
WebAppContext context = new WebAppContext();
context.setContextPath("");
context.setWar(new File("."));
server.addHandler(context);
context.addServlet(DriverServlet.class"/wd/*");
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(3001);
server.addConnector(connector);
server.start();

Question 38:
But what are the advantages of using Remote WebDriver over WebDriver?
Answer
You can use Remote WebDriver when –
·         When you want to execute tests on a browser not available to you locally
·         Introduction to extra latency to tests
But there is one disadvantage of using Remote WebDriver that you would need external servlet container.

Question 39:
Can you show me code example of using Remote WebDriver?
Answer
// Any driver could be used for test
DesiredCapabilities capabilities = new DesiredCapabilities();
// Enable javascript support
capabilities.setJavascriptEnabled(true);
// Get driver handle
WebDriver driver = new RemoteWebDriver(capabilities);
// Launch the app
driver.get("http://www.google.com");

Question 40:
What are the modes of Remote WebDriver
Answer
Remote WebDriver has two modes of operations –
Client Mode: This is where language bindings connect to remote instance. FF drive and RemoteWebDriver clients work this way.
Server Mode: In this mode language bindings set up the server. ChromeDriver works this way.

Question 41:
What Design Patterns could be used while using Selenium 2.0?
Answer
These three Design Patterns are very popular while writing Selenium 2.0 tests –
·         Page Objects – which abstracts UI of web page
·         Domain Specific Language – which tries to write tests which could be understood by a normal user having no technical knowledge
·         Bot Style Tests – it follows “command-like” test scripting

Question 42:
So do I need to follow these Design patterns while writing my tests?
Answer
Not at all, these Design Patterns are considered best practices and you can write you tests without following any of those Design Patterns, or you may follow a Design Pattern which suites your needs most.

Question 43:
Is there a way to enable java script while using HTMLUnitDriver?
Answer
Use this –
HtmlUnitDriver driver = new HtmlUnitDriver();
driver.setJavascriptEnabled(true);
or this –
HtmlUnitDriver driver = new HtmlUnitDriver(true);

Question 44:
Is it possible to emulate a browser with HTMLUnitDriver?
Answer
You can emulate browser while using HTMLUnitDriver but it is not recommended as applications are coded irrespective of browser you use. You could emulate Firefox 3 browser with HTMLUnitDriver as –

HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3);
Or you can inject desired capabilities while instantiating HTMLUnitDriver as –
HtmlUnitDriver driver = new HtmlUnitDriver(capabilities);

Question 45:
How do I use iPhone Driver?
Answer
You should start iPhone SDK and build iPhone driver. Down load iPhone development tools and provision profile. Now iPhone driver can connect through HTTP to the iphone simulator. You can also run simulator on another machine in your network and WebDriver could connect to it remotely.

Question 46:
Is it possible to convert Selenium IDE test to WebDriver test?
Answer
For now there is no formatter available to convert Selenium IDE tests to corresponding WebDriver tests, hence simple answer is No. Yes WebDriver style of code can be generated from Selenium IDE

Question 47:
Can WebDriver handle UntrustedSSLCertificates?
Answer
This feature is currently supported in Firefox browser and is awaiting implementation in IE and Chrome drivers.

Question 48:
Can I carry out multiple operations at once while using WebDriver?
Answer
You can use Builder pattern to achieve this. For example if you want to move an element from one place to another you can use this –
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(element)
.moveToElement(otherElement)
.release(otherElement)
.build();
dragAndDrop.perform();

Question 49:
How do I simulate keyboard keys using WebDriver?
Answer
There is a KeyBoard interface which has three methods to support keyboard interaction –
  • sendKeys(CharSequence)- Sends character sequence
  • pressKey(Keys keyToPress) - Sends a key press without releasing it.
  • releaseKey(Keys keyToRelease) - Releases a modifier key
Question 50:
What about Mouse Interaction?
Answer
Mouse interface lets you carry out following operations –
  • click(WebElement element) – Clicks an element
  • doubleClick(WebElement element) - Double-clicks an element.
  • void mouseDown(WebElement element) - Holds down the left mouse button on an element.
  • mouseUp(WebElement element) - Releases the mouse button on an element.
  • mouseMove(WebElement element) - Moves element form current location to another element.
  • contextClick(WebElement element) - Performs a context-click (right click) on an element.
Question 51:
How does Android Webdriver works?
Answer
Android WebDriver uses Remote WebDriver. Client Side is test code and Server side is application installed on android emulator or actual device. Here client and server communicate using JSON wire protocol consisting of Rest requests.

Question 52:
What are the advantages of using Android WebDriver?
Answer
Android web driver runs on Android browser which is best real user interaction. It also uses native touch events to emulated user interaction.
But there are some drawbacks also like, it is slower than headless WebKit driver. XPath is not natively supported in Android web view.

Question 53:
Is there a built-in DSL (domain specific language) support available in WebDriver?
Answer
There is not, but you can easily build your own DSL, for example instead of using –
webDriver.findElement(By.name("q")).sendKeys("Test");
You can create a more composite method and use it –
public static void findElementAndType(WebDriver webDriver, String elementLocator, String testData) {
webDriver.findElement(By.name(elementLocator)).sendKeys(testData);
}
And now you just need to call method findElementAndType to do type operation.

Question 54:
What is grid2?
Answer
Grid2 is Selenium grid for Selenium 1 as well as WebDriver, This allows to –
·         Execute tests on parallel on different machines
·         Managing multiple environments from one point

Question 55:
How do I start hub and slaves machines in grid 2?
Answer
Navigate to you selenium server standalone jar download and execute following command –

java -jar selenium-server-standalone-.jar -role hub
And you start Slave machine by executing following command –
Java –jar selenium-server-.jar –role webdriver  -hub http://localhost:4444/grid/register -port 6666

Question 56:
And how do I run tests on grid?
Answer
You need to use the RemoteWebDriver and the DesiredCapabilities object to define browser, version and platform for testing. Create Targeted browser capabilities as –

DesiredCapabilities capability = DesiredCapabilities.firefox();
Now pass capabilities to Remote WebDriver object –
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);

Following this, hub will take care of assigning tests to a slave machine

Question 57:
What parameters can be passed to grid2?
Answer
You can pass following parameters to grid 2 –
  • -port 4444 (default 4444)
  • -nodeTimeout (default 30) the timeout in seconds before the hub automatically releases a node that hasn't received any requests for more than the specified number of seconds.
  • -maxConcurrent 5 (5 is default) The maximum number of browsers that can run in parallel on the node.