Automation

Writing test case in Selenium WebDriver with simple example

Writing test case in Selenium WebDriver with simple example
easy way to Writing test case in Selenium WebDriver with simple example
In the following post I will go step by step and explain how to write your first test case using Selenium Webdriver and execute it using TestNG.
1. Right click on the src folder ->New -> Package.

2. Provide package name something like com.stm.test and click “Finish”.

3. Right click on the newly created package – > New -> Class.

4. Provide class name as “RegistrationTest” and click Finish.
Writing test case in Selenium WebDriver with simple example

5. Write the code given below for your first test.
I am taking an example of automating register user functionality for demo sitehttp://newtours.demoaut.com
The code for the first test is as follows:

package com.stm.test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;
public class RegistrationTest
{
@Test //This is TestNG annotation
public void testRegister()
{
WebDriver driver = new FirefoxDriver();
driver.get(“http://newtours.demoaut.com/”);
driver.findElement(By.linkText(“REGISTER”)).click();
driver.findElement(By.name(“firstName”)).sendKeys(“User1″);
driver.findElement(By.name(“lastName”)).sendKeys(“Surname1″);
driver.findElement(By.name(“phone”)).sendKeys(“123456789″);
driver.findElement(By.name(“userName”)).sendKeys(“user1@test.com”);
driver.findElement(By.name(“address1″)).sendKeys(“Test Address”);
driver.findElement(By.name(“city”)).sendKeys(“Test City”);
Select select = new Select(driver.findElement(By.name(“country”)));
       select.selectByVisibleText(“ANGOLA”);
driver.findElement(By.name(“email”)).sendKeys(“user1@test.com”);
driver.findElement(By.name(“password”)).sendKeys(“user1″);
driver.findElement(By.name(“confirmPassword”)).sendKeys(“user1″);
driver.findElement(By.name(“register”)).click();
driver.close();
driver.quit();
}
}
6. After finishing the test right click on the test and click on RunAs – >TestNG Test
Writing test case in Selenium WebDriver with simple example
7. After executing the test select the project and press F5 to refresh the project. A new folder “test-results” will get created which will show you the results for the execution. Right click on index.html->open with->web browser to see the execution report.
If you like this post hit like button for facebook and share it!!

Selenium Webdriver Commands list by www.jobinterviewquestionswithanswers.blogspot.in

Selenium Webdriver Commands list
Command                                               Description

driver.get("http://www.google.com"); To open an application
driver.findElement(By.id("passwd-id")); Finding Element using Id
driver.findElement(By.name("passwd")); Finding Element using Name
driver.findElement(By.xpath("//input[@id=’passwd-id’]")); Finding Element using Xpath
element.sendKeys("some text"); To type some data
element.clear(); clear thecontents of a text field or textarea
driver.findElement(By.xpath("//select")); Selecting the value
select.findElements(By.tagName("option")); Selecting the value
select.deselectAll(); This will deselect all OPTIONs from the first SELECT on the page
select.selectByVisibleText("Edam"); select the OPTION withthe displayed text of “Edam”
findElement(By.id("submit")).click(); To click on Any button/Link
driver.switchTo().window("windowName"); Moving from one window to another window
driver.switchTo().frame("frameName"); swing from frame to frame (or into iframes)
driver.switchTo().frame("frameName.0.child"); to access subframes by separating the path with a dot, and you can specify the frame by itsindex too.
driver.switchTo().alert(); Handling Alerts
driver.navigate().to("http://www.example.com"); To Navigate Paeticular URL
driver.navigate().forward(); To Navigate Forward
driver.navigate().back(); To Navigate Backword
driver.close() Closes the current window
driver.quit() Quits the driver and closes every associated window.
driver.switch_to_alert() Switches focus to an alert on the page.
driver.refresh() Refreshes the current page.
driver.implicitly_wait(30) Amount of time to wait
driver.set_script_timeout(30) The amount of time to wait
driver.get_screenshot_as_file('/Screenshots/foo.png') The full path you wish to save your screenshot to
driver.get_screenshot_as_base64() Gets the screenshot of the current window as a base64 encoded string which is useful in embedded images in HTML

Difference between Selenium RC and Selenium Webdriver by www.jobinterviewquestionswithanswers.blogpot.com

Difference between Selenium RC and Selenium Webdriver by www.jobinterviewquestionswithanswers.blogpot.com



Required to start server before executing the test script.
Doesn’t required to start server before executing the test script.
It is standalone java program which allow you to run Html test suites.
It actual core API which has binding in a range of languages.
Core engine is Javascript based
Interacts natively with browser application
It is easy and small API
As compared to RC, it is bit complex and large API.
API’s are less Object oriented
API’s are entirely Object oriented
It doesn’t supports of moving mouse cursors.
It supports of moving mouse cursors.
Need to append full xpath with ‘xpath=\\’ syntax
No need to append full xpath with ‘xpath=\\’ syntax
It does not supports listeners
It supports the implementation of listeners
It does not support to test iphone/Android applications.
It support to test iphone/Android applications.

100 Selenium Webdriver interview questions with answers by www.jobinterviewquestionswithanswers.blogspot.com

100 Selenium Webdriver interview questions with answers by http://jobinterviewquestionswithanswers.blogspot.in/



1.  Difference between Absolute path & Relative path.
Absolute path will start with root path (/) and Relative path will from current path (//)
Absolute xPath : /html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[1]/div/div[@id='main']/div[@id='Blog1']/div[1]/div[1]/div/div[1]/div/h3/a

Relative xPath : //h3/a[text()='Working on New Window']
2.  Tell me some TestNG Annotations.
@Test,@Parameters,@Listeners,@BeforeSuite,@AfterSuite,@BeforeTest,@AfterTest,
@DataProvider,@BeforeGroups,@AfterGroups,@BeforeClass,@AfterClass,
@BeforeMethod,@AfterMethod,@Factory

3.  What are desired capabilities?
Desired Capabilities help to set properties for the Web Driver. A typical use case would be to
set the path for the Firefox Driver if your local installation doesn't correspond to the default
settings.
4.  Difference between Selenium RC and Selenium Web driver.
 Difference between Selenium RC and Selenium Web driver.

Selenium RC
Selenium Web driver
Selenium RC’s architecture is way more complicated.
Web Driver’s architecture is simpler than Selenium RC’s.
Selenium RC is slower since it uses a JavaScript program called Selenium Core.This Selenium Core is the one that directly controls the browser, not you.
Web Driver is faster than Selenium RC since it speaks directly to the browser uses the browser’s own engine to control it.
Selenium Core, just like other JavaScript codes, can access disabled elements.
Web Driver interacts with page elements in a more realistic way.
Selenium RC’s API is more matured but contains redundancies and often confusing commands.
Web Driver’s API is simpler than Selenium RC’s. It does not contain redundant and confusing commands.
Selenium RC cannot support the headless HtmlUnit browser. It needs a real, visible browser to operate on.
Web Driver can support the headless HtmlUnit browser.
Selenium RC Has Built-In Test Result Generator. Selenium RC automatically generates an HTML file of test results. 
Web Driver has no built-in command that automatically generates a Test Results File.
Selenium RC needs the help of the RC Server in order to do so.
web Driver directly talks to the browser
Selenium RC can support new browsers
It cannot readily support new browsers
5.  Difference between Web driver listener and  TestNG Listener.
TestNG and Web driver Listener have different interfaces to implement and call them. They both
modify respective behaviour. You can use Listeners in Annotation. Below 2 URL gives the
 detailed  list of listener and their interfaces.
6. Describe your framework.
Refer automation link
7.  Which is the best way to locate an element?
Finding elements by ID is usually going to be the fastest option, because at its root, it eventually calls down to document.getElementById(), which is optimized by many browsers.

Finding elements by XPath is useful for finding elements using very complex selectors, and is the most flexible selection strategy, but it has the potential to be very slow, particularly in IE. In IE 6, 7, or 8, finding by XPath can be an order of magnitude slower than doing the same in Firefox. IE provides no native XPath-over-HTML solution, so the project must use a JavaScript XPath implementation, and the JavaScript engine in legacy versions of IE really is that much slower.


If you have a need to find an element using a complex selector, I usually recommend using CSS Selectors, if possible. It's not quite as flexible as XPath, but will cover many of the same cases, without exhibiting the extreme performance penalty on IE that XPath can.
8.  Why we refer Firefox driver to the web driver  inheritance. 
web Driver driver = new FireFoxDriver();
WebDriver is an interface which contain several abstract methods such as get(...), findElamentBy(...) etc.
We simply create reference of web Driver and we can assign objects (Firefox driver, CromeDriver, IEDriver, Andriod driver etc) to it.
Ex :
WebDriver driver = new FireFoxDriver();-----------(1)
If we are using (1) we can do the same thing by using
FireFoxDriver driver = new FireFoxDriver();---------(2)
We can use (1) and (2) for same purpose but if we want to switch to another browser in same program
then again we have to create the object of other class as for example
CromeDriver driver = new CromeDriver();.
creating object of several class is not good. So we create the reference of WebDriver and
we assign the objects of another class as for example
WebDriver driver; // it is created only one time in the program
driver = new FireFoxDriver();// any where in the program
driver = new CromeDriver(); // any where in the program
9.  What are the features of TestNG?
TestNG is a testing framework designed to simplify a broad range of testing needs, from
unit testing (testing a class in isolation of the others) to integration testing (testing entire
systems made of several classes, several packages and even several external frameworks,
 such as application servers). You can use test suite,annotations, automatically generation
 of report and much more.
10.   What is the difference between thread.Sleep()  and selenium. Set Speed ("2000")?
If the application is taking time to load the page then we use selenium.waitforpageload(" "). This command is doesn’t wait upto the given time whenever the page load is completed.
If the application is taking time to refresh the page, then we use Thread. Sleep ( ).it is a standard wait it simply wait to the given time.
selenium.setSpeed
 1. Takes a single argument in string format
 Ex: selenium.setSpeed("2000") - will wait for 2 seconds
 2. Runs each command in after setSpeed delay by the number of milliseconds mentioned in set Speed.
 thread.sleep
 1. Takes a single argument in integer format
 ex: thread. Sleep(2000) - will wait for 2 seconds
 2. Waits for only once at the command given at sleep.

Download Next 90 Selenium webdriver interview  Questions and answers From 

https://drive.google.com/file/d/0B6bhRbDoX68pX3VjLV9kYzV3am8/edit?usp=sharing

Top 25 Selenium Webdriver Interview Questions and answers

Webdriver (Selenium ) Interview Questions and answers

Question 1: What is Selenium 2.0
Answer: Webdriver is open source automation tool for web application. WebDriver is designed to provide a simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC API.

Question 2: What is cost of webdriver, is this commercial or open source.
Answer: selenium  is open source and free of cost.

Question 3: how you specify browser configurations with Selenium 2.0?
Answer:  Following driver classes are used for browser configuration
  • AndroidDriver,
  • ChromeDriver,
  • EventFiringWebDriver,
  • FirefoxDriver,
  • HtmlUnitDriver,
  • InternetExplorerDriver,
  • IPhoneDriver,
  • IPhoneSimulatorDriver,
  • RemoteWebDriver
Question 4: 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.

Question5: Can you show me one code example of setting Selenium 2.0?
Answer: below is example
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/");
driver.findElement(By.cssSelector("#gb_2 > span.gbts")).click();
driver.findElement(By.cssSelector("#gb_1 > span.gbts")).click();
driver.findElement(By.cssSelector("#gb_8 > span.gbts")).click();
driver.findElement(By.cssSelector("#gb_1 > span.gbts")).click();

Question 6: 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 7: 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. className ("CalssName”));
driver.findElement(By. linkText ("LinkeText”));
driver.findElement(By. partialLinkText ("PartialLink”));
driver.findElement(By. tagName ("TanName”));
driver.findElement(By.xpath("XPathLocator));

Question 8:  How do I submit a form using Selenium?
Answer:
WebElement el  =  driver.findElement(By.id("ElementID"));
el.submit();

Question 9: How to capture screen shot in Webdriver?
Answer:
File file= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file, new File("c:\\name.png"));

Question 10: How do I clear content of a text box in Selenium 2.0?
Answer:  
WebElement el  =  driver.findElement(By.id("ElementID"));
el.clear();

Question 11:  How to execute java scripts function.
Answer:
JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("pass your java scripts");

Question 12:  How to select a drop down value using Selenium2.0?
Answer: See point 16 in below post: 

Question 13: How to automate radio button in Selenium 2.0?
Answer:
WebElement el = driver.findElement(By.id("Radio button id"));

//to perform check operation
el.click()

//verfiy to radio button is check it return true if selected else false
el.isSelected()

Question 14: How to capture element image using Selenium 2.0?

Question 15: How to count total number of rows of a table using Selenium 2.0?
Answer: 
List {WebElement} rows = driver.findElements(By.className("//table[@id='tableID']/tr"));
int totalRow = rows.size();

Question 16:  How to capture page title using Selenium 2.0?
Answer:
String title =  driver.getTitle()

Question 17:  How to store page source using Selenium 2.0?
Answer:
String pagesource = driver.getPageSource()

Question 18: How to store current url using selenium 2.0?
Answer: 
String currentURL  = driver.getCurrentUrl()

Question 19: How to assert text assert text of webpage using selenium 2.0?
Answer:
WebElement el  =  driver.findElement(By.id("ElementID"));
//get test from element and stored in text variable
String text = el.getText();

//assert text from expected
Assert.assertEquals("Element Text", text);

Question 20: How to get element attribute using Selenium 2.0?
Answer:
WebElement el  =  driver.findElement(By.id("ElementID"));
//get test from element and stored in text variable
String attributeValue = el. getAttribute("AttributeName") ;

Question 21: How to double click on element using selenium 2.0?
Answer:
WebElement el  =  driver.findElement(By.id("ElementID"));

Actions builder = new Actions(driver);
builder.doubleClick(el).build().perform();

Question 22: How to perform drag and drop in selenium 2.0?
Answer:
WebElement source  =  driver.findElement(By.id("Source ElementID"));
WebElement destination  =  driver.findElement(By.id("Taget ElementID"));

Actions builder = new Actions(driver);
builder.dragAndDrop(source, destination ).perform();

Question 23: How to maximize window using selenium 2.0?
Answer:
driver.manage().window().maximize();

Older Posts