Sei sulla pagina 1di 401

JUNIT INTERVIEW QUESTIONS

Interview Questions

What Is JUnit?
Who Should Use JUnit, Developers or Testers?
Why Do You Use JUnit to Test Your Code?
Do You Know the Book "JUnit Recipes: Practical Methods for Programmer
Testing"?
Do You Know the Book "JUnit in Action"?
Where Do You Download JUnit?
How Do You Install JUnit?
What Articles Have You Read about JUnit?
How To Wirte a Simple JUnit Test Class?
How To Compile a JUnit Test Class?
How To Run a JUnit Test Class?
What CLASSPATH Settings Are Needed to Run JUnit?
How Do I Run JUnit Tests from Command Window?
How Do You Uninstall JUnit?
How To Write a JUnit Test Method?
Can You Provide a List of Assertion Methods Supported by JUnit 4.4?
What Happens If a JUnit Test Method Is Declared as "private"?
What Happens If a JUnit Test Method Is Declared to Return "String"?
Why Does Poeple Import org.junit.Assert Statically?
How To Group Multiple Test Classes into a Suite in JUnit 4.4?
How To Run a "@Suite.SuiteClasses" Class in JUnit 4.4?
What Is the "@SuiteClasses" Annotation?
Why Not Just Use a Debugger for Unit Testing?
Why Not Just Write a main() Method for Unit Testing?
Why Not Just Use System.out.println() for Unit Testing?
Under What Conditions Should You Test set() and get() Methods?
Under What Conditions Should You Not Test Get() and Set() Methods?
Do You Need to Write a Test Class for Every Class That Need to Be
Tested?
What Is JUnit TestCase?
What Is JUnit TestSuite?
How Many Test Runners Are Supported in JUnit 3.8?
What Are JUnit 3.8 Naming Conventions?
How To Write a Single Class to Define Multiple Tests and Run Them?
How to Run Your JUnit 4.4 Tests with a JUnit 3.8 Runner?
Can You Write a Simple Class for JUnit Testing in 1 Minute?
Can You Write a JUnit Test Case Class in 2 Minutes?
Can You Write a JUnit Test Suite in 2 Minutes?
Where Should You Place Test Classes?
How Do You Test a "protected" Method?
How Do You Test a "private" Method?
Can You Write a JUnit Test Case Class in 10 Minutes?
Can You Explain a Sample JUnit Test Case Class?
Do You Need to Write a main() Method in a JUnit Test Case Class?
How To Group Test Cases Class using JUnit TestSuite?
Can You Write a JUnit 4.4 Test Class Template in 2 Minutes?
Can You Explain the Life Cycle of a JUnit 4.4 Test Class?
How To Write Setup Code to Run Once for All Tests in a Test Class?
Can You Write a JUnit 3.8 Test Class Template in 2 Minutes?
Can You Explain the Life Cycle of a JUnit 3.8 Test Case Class?
What Is a JUnit Test Fixture?
Can You Create Tests without Using a Common Test Fixture?
How Create a Test Fixture to Be Shared by All Tests in a Test Class?
How To Destroy a JUnit Test Fixture?
When Do You Need to Write an @After Method?
When Should Unit Tests Should Be Written In Development Cycle?
How Do You Launch a Debugger When a Test Fails?
How Do You Run JUnit Using Ant?
How Do You Run All Test Classes without Managing a TestSuite Explicitly?
How Do You Test an Expected Exception with JUnit?
How To Use the "expected" Parameter Supported by the "@Test"
Annotation?
How Do You Test an Unexpected Exception with JUnit?
What Happens If a Test Method Throws an Exception?
Why Do I See "Unknown Source" in the Stack Trace of a Failed Test?
How Do You Test a Method That Doesn't Return Anything?
When Objects Are Garbage Collected After a Test Is Executed?
What Is Java "assert" Statement?
How To Test Programs Thats Use Java "assert" Statements?
Should You Run JUnit Tests with Java Assertion Disabled?
What Happens If You Run JUnit Tests with Java Assertion Enabled?
Why Does JUnit Only Report the First Failed Assertion in a Single Test?
Do You Have To Write a Test for Everything?
How Often Should You Run Your JUnit Tests?
What Do You Do When a Defect Is Reported?
How simple is 'too simple to break'?
How To Verify the JUnit Plugin in Eclipse?
How To Create Test Class in Eclipse?
How to Run a JUnit Test Case in Eclipse?
Can You Describe Steps of Creating Test Case Classes in Eclipse?
How to creating a Test Suite using JUnit in Eclipse?
How Do You Use Ant to Create HTML Test Reports?
How Do You Test Classes That Must Be Run in a J2EE Container?
Can You Explain the Exception: "No runnable methods"?

-----------------------------------------------------------------------------------------

Transcript of Selenium and WebDriver
Selenium What is Selenium? The name comes from the Greek selene meaning "Moon"
Selenium 1, bye-bye! WebDriver Selenium occurs in three distinct forms: as a non-crystalline
(gray);
it can form
as a deep
red to black
powder; and it can form as red crystals. Selenium is a chemical element with atomic number 34,
chemical symbol Se, and an atomic mass of 78.96. It is a nonmetal, whose properties are
intermediate between those of adjacent chalcogen elements sulfur and tellurium. In nature In
testing The tests can then be run against most modern web
browsers. Selenium deploys on
Windows, Linux,
and Macintosh platforms.

Thank you! Selenium is a portable software testing framework for web applications.
Selenium provides a record/playback tool for authoring tests without learning a test scripting
language (Selenium IDE). It also provides a test domain-specific language (Selenese) to write
tests in a number of popular programming languages, including C#, Java, Groovy, Perl, PHP,
Python and Ruby. :
http://www.cs.colostate.edu
http://www.sibgames.net
http://demiart.ru
http://www.spletnik.ru 7.WebDriver is on its way to
becoming a browser standard. WebDriver: WebDriver
What is it?
What does it do? WebDriver is a tool for automating testing web applications, and in particular
to verify that they work as expected. It aims to provide a friendly API that's easy to explore and
understand, which will help make your tests easier to read and maintain. It's not tied to any
particular test framework, so it can be used equally well with JUnit, TestNG or from a plain old
"main" method. And then?! And what's the difference between
WebDriver and Selenium? The main difference is hidden in the architecture of these tools
Comparison Let's look at these differences
a bit more closely! Here the presentation comes to an end... 5. Window
An interface for managing size and
position of window browser Interface WebDriver The main interface used for testing, which
represents an idealised web browser.
The methods in this class fall into three categories: - Control of the browser itself (get(),
navigate(), close(), etc)

- Selection of WebElements (findElement(), findElements(), etc)

- Debugging aids (getCurrentUrl(), getPageSource(), getWindowHandles(), etc) WebDriver has
six major Interfaces : 0. ImeHandler
An interface for managing input methods 1. Navigation
Used to move between sites in the current window 2. Options
An interface for managing stuff you would do in a browser menu 3. TargetLocator
Used to locate a given frame or window 4. Timeouts
An interface for managing timeout behavior for WebDriver instances. Let's start! Locating UI
Elements 2. Once youve finished filling out the form, you probably want to submit it. One way
to do this is would be to find the submit button and click it:

driver.findElement(By.id("submit")).click(); Alternatively, WebDriver has the convenient
"submit" method on every element:

element.submit(); Select multiple items

driver.get("http://jqueryui.com/demos/selectable/");

WebElement item1 = driver.findElement(By.xpath("//li[.='Item 1']"));
WebElement item2 = driver.findElement(By.xpath("//li[.='Item 2']"));

//First, configure it:
Actions builder = new Actions(driver);
builder.clickAndHold(item1)
.clickAndHold(item2)
.click() ;

//Then get the action:
Action selectMultiple = builder.build();

//And execute it:
selectMultiple.perform(); Tips, Hacks & Hidden Features Javascript Alerts WebDriver supported
Javascript alerts

// Get a handle to the open alert, prompt or confirmation
Alert alert = driver.switchTo().alert();

// Get the text of the alert or prompt
alert.getText();

// And acknowledge the alert (equivalent to clicking "OK")
alert.accept(); Drag And Drop Drag an element to an offset

driver.get("http://jqueryui.com/demos/draggable/");
WebElement dragItem = driver.findElement(By.id("draggable"));
(new Actions(driver)).dragAndDropBy(dragItem, 5, 10).build().perform(); Press control+...

textBox.sendKeys(Keys.LEFT_CONTROL + "a");
textBox.sendKeys(Keys.LEFT_CONTROL + "c");
textBox.sendKeys(Keys.LEFT_CONTROL + "v");
textBox.sendKeys(Keys.LEFT_CONTROL, Keys.F5); Sequence of actions Proxy Proxy
configuration

Proxy proxy = new Proxy();
proxy.setProxyAutoconfigUrl("http://yourdomain/config");
DesiredCapabilities capabilities =
DesiredCapabilities.firefox();
capabilities.setCapability(CapabilityType.PROXY, proxy); Scrolls a window It is possible to use
Javascript execution abilities:

int pixel = 500;
((JavascriptExecutor) driver)
.executeScript("if (window.screen){window.scrollBy(0," + pixel + ");};"); Start Firefox with an
extension installed File file = new File("firebug-1.9.0-fx.xpi");
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.addExtension(file);
WebDriver driver = new FirefoxDriver(firefoxProfile); By ID

This is the most efficient and prefered way to locate an element. Common pitfalls that UI
developers make is having non-unique ids on a page or auto-generating the id, both should be
avoided. A class on an html element is more appropriate than an auto-generated id.

WebElement captchaBox = driver.findElement(By.id("ConfirmMainEmailForm_captcha")); By
Name

Finds the element with matching name attribute.

WebElement captchaBox = driver.findElement(By.name("ConfirmMainEmailForm[captcha]"));
By Link Text

Find the link element with matching visible text.

WebElement signInButton =
driver.findElement(By.linkText("Sign in and register")); By Partial Link Text

Find the link element with partial matching visible text.

WebElement signInButton =
driver.findElement(By.partialLinkText("Sign in")); By CSS

Like the name implies it is a locator strategy by css.
Please,beware that not all browsers were created equal, some css that may work in one version -
may not work in another.

WebElement signInButton = driver.findElement(By.cssSelector(".bUserBar .LikeRealBtn")); By
XPATH

At a high level, WebDriver uses a browsers native XPath capabilities wherever possible.

List<WebElement> radioButtons =
driver.findElements(By.xpath("//input[@class='bTicketPaper__eRadioButton']"));
List<WebElement> radioButtonsVisible =
driver.findElements(By.xpath("//input[@class='bTicketPaper__eRadioButton' and
not(@disabled='disabled')]")); Let's solve the problem:
Find all radio buttons circled in the picture The same result we get if we use as a locator class
name.

By Class Name

Class in this case refers to the attribute on the DOM element. Often in practicle use there are
many DOM elements with the same class name, thus finding multiple elements becomes the
more pratical option over finding the first element.

List<WebElement> radioButtons =
driver.findElements(By.className("bTicketPaper__eRadioButton")); I almost forgot ... By Tag
Name

The DOM Tag Name of the element.

Let's resolve the issue: How do We get the entire text of the page? WebElement bodyOfPage =
driver.findElement(By.tagName("body"));
String bodyText = bodyOfPage.getText(); 0. Locating UI Elements
Each of the language bindings expose a Find Element and Find Elements method.

The Find methods take a locator or query object called By. By strategies are listed further.
1. Typing into an element
If you want to enter some text into a text field, then you can use:

element.sendKeys("some text");

A side-effect of this is that typing something into a text field wont automatically clear it.
Instead, what you type will be appended to whats already there. You can easily clear the
contents of a text field or textarea:

element.clear(); Work with a slider

driver.get("http://jqueryui.com/demos/slider/range.html");
WebElement dragItem =
driver.findElement(By.xpath("//a[@class='ui-slider-handle ui-state-default ui-corner-all']"));
(new Actions(driver)).dragAndDropBy(dragItem, 10, 0).build().perform(); Drag an element to
drop on to another element

driver.get("http://jqueryui.com/demos/droppable/");
WebElement fromItem1 = driver.findElement(By.id("draggable"));
WebElement toItem2 = driver.findElement(By.id("droppable"));
(new Actions(driver)).dragAndDrop(fromItem1, toItem2).build().perform(); Executing JavaSript

WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("alert('Selenium1 bye-bye')"); 1. Selenium works through proxy using
Javascript. 1. WebDriver works natively with Browser
(Native automation faster and a little less
prone to error and browser configuration).
2. Selenium supports major browsers.
(IE, Firefox, Chrome, Safari, Opera) 2. WebDriver supports IE, Firefox, Opera,
Chrome, and also Android and IPhone Drivers. 3. Selenium API is quite complicated 3. Great
Simple API. 4. Selenium supports multiple
languages to write the test.
(C#, Java, Groovy, Perl, PHP,
Python and Ruby) 4. Perl and PHP are not supported in WebDriver
(December 2011).
A pure JS API support is also in the planning stage. 5. Selenium-RC Server's start-up
is required.
5. Does not Requires Selenium-RC Server
to be running. 6. Access to headless HTMLUnit
can allow really fast tests. Selenium: Bugs are found by tests, not by automation Presentation
Agenda 0. What is Selenium? 1. Comparison:
Selenium RC vs WebDriver 2. Interface WebDriver.
Tips, Hacks & Hidden Features 3. Migrating from
Selenium RC to WebDriver The most important Commands
and Operations... Also, you can simulate pressing the arrow keys by using the Keys class:

element.sendKeys("s", Keys.ARROW_DOWN);

It is possible to call sendKeys on any element, which makes it possible to test keyboard shortcuts
such as those used in GMail. WebElement loginElement =
driver.findElement(By.name("AuthForm[loginOrEmail]"));

loginElement.clear();
loginElement.sendKeys("selenium1byebye@gmail.com");
driver.findElement(By.xpath("//input[contains(@value,'Sign in')]")).click(); Evgeny Tkachenko
Senior Software Automation Testing Engineer Evgeny Tkachenko Senior Software Automation
Testing Engineer evgenij.tkachenko@inn.ru our blog: http://www.innovatesting.info/ How to
migrate to WebDriver ? Just "to Cut off" //Get the screen size
java.awt.Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();

//Define the desired size
Dimension maxWindowSize =
new Dimension(screenSize.width -4, screenSize.height-4);

//Set the desired size
WebDriver.Window window = driver.manage().window();
window.setSize(maxWindowSize); WebDriver. Hidden Features. Maximize the window Just
start to use WebDriver API. But you need to rework all your methods in one massive push...
Selenium 1, bye-bye! WebDriver. Hidden Features. Use WebDriver-Backed Selenium-RC... The
Java version of WebDriver provides an implementation of the Selenium-RC API.
This means that you can use the underlying WebDriver technology using the Selenium-RC API.
File profileDir = new File("SeleniumProf");
FirefoxProfile firefoxProfile = new FirefoxProfile(profileDir);
WebDriver driver = new FirefoxDriver(firefoxProfile); WebDrivers API is more Object
Oriented than the original Selenium RC API. Setting the path to Firefox You have write this line
before opening the browser System.setProperty("webdriver.firefox.bin","pathtofirefox.exe");
WebDriver (Selenium 2.0) is the merging of the Selenium and WebDriver projects.
RemoteWebDriver
Taking a Screenshot //Start Selenium Server with Java Code
RemoteControlConfiguration rcc = new RemoteControlConfiguration();
rcc.setTrustAllSSLCertificates(true);
SeleniumServer seleniumServer = new SeleniumServer(rcc);
if (!seleniumServer.getServer().isStarted())
{
seleniumServer.start()
}

// customize your capabilities here
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
...

// RemoteWebDriver does not implement the TakesScreenshot class
// but We can create MyRemoteWebDriver by extending RemoteWebDriver
// and implementing TakesScreenshot interface.
driver = new MyRemoteWebDriver(new URL("http://machineIP:port/wd/hub"),capabilities);
class MyRemoteWebDriver extends RemoteWebDriver implements TakesScreenshot {

...

public MyRemoteWebDriver(URL remoteAddress,
Capabilities desiredCapabilities) {
super(remoteAddress, desiredCapabilities);
}

@Override
public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
if ((Boolean) getCapabilities().getCapability(CapabilityType.TAKES_SCREENSHOT)) {
String base64Str = execute(DriverCommand.SCREENSHOT).getValue().toString();
return target.convertFromBase64Png(base64Str);
}
return null;
}


}

--------------------------------------------------------------------------------------------

Automation Framework Design Structure.

Perquisites for automation frame work.
What are all needed for designing automation framework?


Folder Structure for Automation frame work.






1. Create a Java Project and add the library files into JRE System Library.
The folder structure will be.

a. Test Util.Java
b. Test Data
c. OR. Properties.
d. Tests(or Classes).java
e. Driver Script. Java
f. Library files
g. testing.xml
h. Screen shots.
i. Test output

Now we will discuss about the frame work how to design and how to
work with framework.

Before that we will discuss about each and every packages (Each
script file).

a. Library Files which need to add...
Note: No need to download each and every jar. Just download the
below jars which contains all from the below given link.
Link : Seleniumhq.org/Download/





b. Test Util.java:
--- This package is mainly deals with utilities. like..

Initialize.
get Object.
waitForElementPopulate
WaitForElementPresent
waitFor5Seconds
typeData
getExcelData
take Screenshot
test Login
selectFromDropdown


Initialize. In initialization we need to read the property file data. Like below

public static void intialize() throws IOException {
try {
props = new Properties();
fis = newFileInputStream(System.getProperty("user.dir")+"\\src\\
OR.properties");
System.out.println(fis);
props.load(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

****** here we have to create an instance for properties and read
through file input stream and load the props file .

get Object.

Get object concept will use in the test scripts. Like
public WebElement getObject(String xpathkey) throws IOException {
try {
return driver.findElement(By.xpath(props.getProperty(xpa
thkey)));
} catch (Throwable t) {
System.out.println("error:\t" + xpathkey);
return null;
}
}
Here we have to use this method as
getObject(Xpath given in the property file).click();
getObject(Xpath).getTitle();
getObject(Xpath).getText();...etc...in the test scripts

waitForElementPopulate : this method will use in case of any
public void waitForElementPopulate(String xpathkey) throws Exception
{

int i = 0;
String expdata = null;
while (i <= 20) {
System.out.println(expdata + "\t" + i);
Thread.sleep(2000L);
new Actions(driver).moveToElement(getObject(xpathkey)).click().p
erform();
getObject(xpathkey).click();
Thread.sleep(2000L);
expdata = getObject(xpathkey).getText().trim();
System.out.println(expdata);
if (expdata != null) {
System.out.println(expdata);
break;
} else {
Thread.sleep(500L);
i++;
}
}
}

Ex: waitForElementPopulate(xpathkey);
WaitForElementPresent: It will wait for Element present in the Web page. Until
the web element present in the web page it will wait.
public WebElement WaitForElementPresent(String xpathkey) throws Exception {

WebElement present = null;
int i = 0;
while (i <= 10) {
Thread.sleep(2000L);
present = getObject(xpathkey);
if (present != null) {
break;
} else {
System.out.println("i is: "+i);
i++;
}
}
return present;
}

Ex: WaitForElementPresent(propertyfilexpath);
WaitFor5Seconds: it will wait for 5 second to execute a single line or
command.

public void waitFor5Seconds() throws Exception {

int i = 0;
while (i <= 5) {
Thread.sleep(1000L);
System.out.println("i is: "+i);
i++;
}
}
Ex: waitFor5Seconds();
TypeData : this will help you to enter the data in Text field.

public void typeData(String xpathkey, String value) throws Exception {

try {
getObject(xpathkey).sendKeys(value);
} catch (Exception t) {
t.printStackTrace();
}
}
Ex: TypeData(Xpath from propertyfile,Value you want to enter into text field);
GetExcelData(Xpath,SheetName,TableName1,Tablename2);
This method will read the excel data and send the data into text
fields in the application.
public String[][] getExcelData(String xlPath, String shtName, String tbName, String
tbName1)throws Exception{
String[][] tabArray=null;
Workbook workbk = Workbook.getWorkbook(new File(xlPath));
Sheet sht = workbk.getSheet(shtName);
int sRow,sCol, eRow, eCol,ci,cj;
Cell tableStart=sht.findCell(tbName);
sRow=tableStart.getRow();
sCol=tableStart.getColumn();
Cell tableEnd= sht.findCell(tbName1);
eRow=tableEnd.getRow();
eCol=tableEnd.getColumn();
System.out.println("startRow="+sRow+", endRow="+eRow+",
" + "startCol="+sCol+", endCol="+eCol);
tabArray=new String[eRow-sRow-1][eCol-sCol-1];
ci=0;
for (int i=sRow+1;i<eRow;i++,ci++){
cj=0;
/*System.out.println("Row"+i);
System.out.println("Column"+sCol);*/
for (int j=sCol+1;j<eCol;j++,cj++){
/*System.out.println("Row1"+i);
System.out.println("Column1"+j);*/
tabArray[ci][cj]=sht.getCell(j,i).getContents();
}
}
return(tabArray);
}
takeScreenShot : This will take the screen shot where you mentioned
the below line of code.

public void takeScreenShot(String fileName,String folderName,String Modname
) throwsIOException
{
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, newFile(System.getProperty("user.dir")+"//screenshots
//"+folderName+"//"+Modname+"//"+fileName+".png"));
}

Ex: takeScreenShot(Filename,folder,Modname);

TestLogin: this method useful to direct login to the application.

public void testLogin(String UserName, String Password) throws Exception {
if (getObject("login.username.label")
!= null && getObject("login.pwd.label") != null) {

typeData("en.distributor.UName", UserName);
typeData("en.distributor.Pwd", Password);
getObject("en.distributor.LgBtn").submit();
System.out.println("Clicked on Login button");
waitFor5Seconds();
}
}
Ex: testLogin(UserName, Password); or testLogin(Admin, 111);
SelectfromDropDown: this will select an option from drop down list.

public void selectFromDropdown(String xpathkey, String value) throws Exception{
/*waitFor5Seconds();*/
WebElement table6 = getObject(xpathkey);
List<WebElement> tds6 = table6.findElements(By.tagName("option"));
for (WebElement option : tds6) {
if (option.getText().equals(value)) {
option.click();
}
}


So far we discussed about TestUtil file....
Now we are going to discuss about the test data.

2. Test Data :
This is an excel file which contains Test data to test the
application. Please find the sample test data file.
GetExcelData(Location,SheetName,TableName1,Tablename2);



3. OR. Properties.

This is very crucial concept need to concentrate . because the
properties are stored in the Property file. I will show you the sample.




4. Tests(.Java files)
We will check with sample script for Gmail Login.
package Gmail;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import TestUtil.TestUtil;
public class GmailLogin extends TestUtil
{
public String location = "path of Xls file";
public String sheetname1 = "GmailLogin";
public String Baseurl = "http://mail.google.com";
@BeforeClass
public void setUp(){
driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get(Baseurl);
}
@Test(dataProvider="dp")
public void GLogin(String UserName,String Password) throws Exception{

// enter the username and password.
testLogin(UserName, Password);
waitFor5Seconds();

if(getObject("login.login_Btn")!=null){
WaitForElementPresent("login.login_Btn");
//Click on login button
getObject("login.login_Btn").click();
}else{
takeScreenShot("GmailLogin","Gmailtest", "Gmail");
}
}

@DataProvider(name = "dp")
public Object[][] createData() throws Exception {
Object[][] retObjArr = getExcelData(location, sheetname1,
"GmailLogin", "GmailLogout");
return (retObjArr);
}
}
5. TestNg.xml




----------------------------------------------------------------------------------------
1. I want to run all the tests in sequence.



I added the preserve-order parameter in the suite. The tests run in the
order we specified.

<suite name="Suite" preserve-order="true">

2. I want to run the tests in multiple browser ? show me with code and xml
file.

Ans:
MULTI BROWSER TESTING USING SELENIUM TESTNG
This Section describes how to run your Test cases on different browsers.

Few Simple steps Using TestNG :)

Step 1: Create your Script. Using TestNG annotations. Define parameters
(using @Parameters) for taking input value i.e, which browser should be used
for Running the Test

Step 2: Create a TestNG XML for running your script

Step 3: Configure the TestNG XML for passing parameters i.e, to tell which
browser should be used for Running the Test

Step 4: Run the TestNG XML which can pass the appropriate browser name to
the Script such that the Test Case is executed in a specified browser


Programatically this can be Done as follows:

Step 1:

package atu.multibrowser;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class MultiBrowserTest {
private WebDriver driver;
// Configure for multi browser drivers
@Parameters("browser")
@BeforeClass
public void beforeTest(String browser) {
if (browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
} else if (browser.equalsIgnoreCase("chrome")) {
// Set Path for the executable file
System.setProperty("webdriver.chrome.driver",
"D:\\chromedriver.exe");
driver = new ChromeDriver();
} else if (browser.equalsIgnoreCase("ie")) {
// Set Path for the executable file
System.setProperty("webdriver.ie.driver", "D:\\IEDriverServer.
exe");
driver = new InternetExplorerDriver();
} else {
throw new IllegalArgumentException("The Browser Type is
Undefined");
}
// Open App
driver.get("http://demo.opensourcecms.com/wordpress/wp-login.php");
}
@Test
public void login() throws InterruptedException {
// Enter UserName
driver.findElement(By.id("user_login")).clear();
driver.findElement(By.id("user_login")).sendKeys("admin");
// Enter Password
driver.findElement(By.id("user_pass")).clear();
driver.findElement(By.id("user_pass")).sendKeys("demo123");
// Click on Submit button
driver.findElement(By.id("wp-submit")).submit();
}
@AfterClass
public void afterTest() {
try {
driver.quit();
} catch (Exception e) {
driver = null;
}
}
}



Step 2 & Step 3: The below XML is configured to run the Test Case in Firefox,
Chrome and IE browser in sequential manner
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="none">
<test name="FirefoxTest">
<parameter name="browser" value="firefox" />
<classes>
<class name="atu.multibrowser.MultiBrowserTest" />
</classes>
</test>
<test name="ChromeTest">
<parameter name="browser" value="chrome" />
<classes>
<class name="atu.multibrowser.MultiBrowserTest" />
</classes>
</test>
<test name="IETest">
<parameter name="browser" value="ie" />
<classes>
<class name="atu.multibrowser.MultiBrowserTest" />
</classes>
</test>
</suite>



------------------------------------------------------------
HOW TO SEND AN EMAIL USING SELENIUM
1.public class emil
{
public static String file[] = {System.getProperty("user.dir")+"//test-
output//index.html"};
public static String
toAddress[]={"rameshkudikala83@gmail.com","ramesh.kudikala@NextSphere.c
om","jagadeeswara.urlana@nextsphere.com"};

public static void main(String[] args) throws Exception
{
Mail();
}
public static void Mail() throws Exception
{
if(EmailSender.SendMail("rameshkudikala83@gmail.com", "nani@11210",
"Automation Scripts Report for Australia Market", toAddress, file)){
System.out.println("Email has been sent");
// logger.info("Email has been sent");
}else{
//logger.info("Error occured in sending email");
}
}

}

2. package Enroll;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;

public class EmailSender extends Authenticator {

public static Properties props =null;
public String user=null;
public String pw=null;
public EmailSender(String username,String password){
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
public static boolean SendMail(String fromMail,String password,String
message,String toMail[],String[] attachFiles) throws Exception
{

String host="smtp.gmail.com";
props= System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", fromMail);
props.put("mail.smtp.password", password);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");


Session session = Session.getInstance(props,new EmailSender(fromMail,
password));
MimeMessage mimeMessage=new MimeMessage(session);
try{
mimeMessage.setFrom(new InternetAddress(fromMail));
//now get the address of reciepient
InternetAddress[] toAddress=new InternetAddress[toMail.length];
for(int i=0;i<toMail.length;i++){
toAddress[i]=new InternetAddress(toMail[i]);
}
for(int i=0;i<toAddress.length;i++){
mimeMessage.addRecipient(RecipientType.TO, toAddress[i]);
}
mimeMessage.setSubject("Automation Status");

/*MimeBodyPart attachPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();*/
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");

// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);

/*String file =
"D:/MonaVieWorkSpace/NorthAmericaCoreFeature_US/screenshots/ITR2/Person
alOrder/Ordersummary.png";
String filename="OrderSummaryScreenShot";

DataSource source = new FileDataSource(file);
System.out.println(file);
System.out.println(filename);

attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(new File(file).getName());
multipart.addBodyPart(attachPart);
mimeMessage.setContent(multipart );
System.out.println("Attachment is added");*/

if (attachFiles != null && attachFiles.length > 0) {
for (String filePath : attachFiles) {
MimeBodyPart attachPart = new MimeBodyPart();

try {
attachPart.attachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println("Attachment has been added");
multipart.addBodyPart(attachPart);
}
}

/*mimeMessage.setText(message);*/
mimeMessage.setContent(multipart);
Transport transport=session.getTransport("smtp");
transport.connect(host, fromMail, password);
Transport.send(mimeMessage, mimeMessage.getAllRecipients());

transport.close();
return true;
}catch(MessagingException me){
me.printStackTrace();
}
return false;
}
}


------------------------------------------------------------------------------------
RC PRACTICE SCRIPTS
Xpath


import com.thoughtworks.selenium.DefaultSelenium;


public class Xpath {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DefaultSelenium selenium = new DefaultSelenium("localhost", 6666,
"*iehta", "http://");
selenium.start();
selenium.open("http://mail.in.com");
selenium.windowMaximize();

selenium.type("xpath=/html/body/div[1]/div[2]/div/table/tbody/tr[2]/td[3]/form/div/div[1]/p[3]/input[
@id='f_id']","username");

selenium.type("xpath=/html/body/div[1]/div[2]/div/table/tbody/tr[2]/td[3]/form/div/div[1]/p[5]/input[
@id='f_pwd']","password");

}

}

2. Validation:


import com.thoughtworks.selenium.DefaultSelenium;


public class Validation {

public static DefaultSelenium selenium=new DefaultSelenium("localhost",6666,"*iehta","http://");
public static String Bodytext()
{
selenium.start();
selenium.open("http://google.com");
selenium.windowMaximize();

if(selenium.isTextPresent("Nag"))
{
System.out.println("Already checked");
}
else{
selenium.select("", "label=one");
//selenium.type("q", "selenium");
selenium.check("chkbox");

//System.out.println("Alert is not available");
}

selenium.click("btnG");
return "pass";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Bodytext();

}

}

3. Test DB


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class testdb {
public static Connection connection;
public static Statement statement;
public static ResultSet resultSet;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(
"jdbc:sqlserver://servername;instance=SQLEXPRESS;databaseName=ccdata;","Username",
"Password");
statement = connection.createStatement();
resultSet = statement.executeQuery("select * from emp");
while (resultSet.next()) {
System.out.println("EMPLOYEE NAME:" + resultSet.getString("emp name"));
System.out.println("EMPLOYEE ID:" + resultSet.getString("emp ID"));
}
} catch (Exception e) {
e.printStackTrace();
}

}

}

4. TEST

import com.thoughtworks.selenium.DefaultSelenium;

public class Test {

public static DefaultSelenium selenium = new DefaultSelenium("localhost",
6666, "*iehta", "http://");

public static String fun1() throws Exception

{
try{
selenium.start();
selenium.open("//google.co.in");
Thread.sleep(30000);
selenium.type("q", "selenium");
selenium.click("btnG");

}catch(Exception e)
{

}

return "pass";
}

public static void main(String[] args) throws Exception

{
// TODO Auto-generated method stub
fun1();

}

}

5. Sync:


import com.thoughtworks.selenium.DefaultSelenium;


public class Sync {

/**
* @param args
*/
public static String google() throws Exception
{
DefaultSelenium selenium=new DefaultSelenium("localhost",6666,"*iehta","http://");
selenium.start();
selenium.open("http://mail.in.com");
selenium.windowMaximize();
selenium.type("f_id", "seleniumforum_Nageswar");
selenium.type("f_pwd", "selenium");
// selenium.setTimeout("100000");
selenium.click("//input[@value='' and @type='submit']");
//Thread.sleep(10000);
selenium.waitForPageToLoad("130000");
selenium.click("link=Sign out");
selenium.waitForPageToLoad("130000");
selenium.chooseCancelOnNextConfirmation();
selenium.chooseOkOnNextConfirmation();
return "pass";

}
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
google();

}

}
6. Reusability

import java.io.FileInputStream;

import jxl.Sheet;
import jxl.Workbook;

import com.thoughtworks.selenium.DefaultSelenium;
public class ReusableScript {
public static DefaultSelenium selenium = new DefaultSelenium("localhost",
6666, "*iehta", "http://");
public static String gmail() throws Exception {
selenium.start();
selenium.open("http://www.gmail.com");
selenium.windowMaximize();
Thread.sleep(2000);
selenium.click("link=Create an account ");
selenium.waitForPageToLoad("30000");
return "pass";
}
public static String Register() throws Exception {
FileInputStream fi = new FileInputStream(
"D:\\Framework\\TestData\\Register.xls");
Workbook w = Workbook.getWorkbook(fi);
Sheet s = w.getSheet(0);
for (int i = 1; i < s.getRows(); i++) {
if (!s.getCell(3, i).getContents().equals("")) {
if (s.getCell(2, i).getContents().contains("Text")) {
if (selenium
.isElementPresent(s.getCell(0, i).getContents())) {
selenium.type(s.getCell(0, i).getContents(), s.getCell(
3, i).getContents());
}
} else if (s.getCell(2, i).getContents().contains("Combo")) {
if (selenium
.isElementPresent(s.getCell(0, i).getContents())) {
selenium.select(s.getCell(0, i).getContents(), "label="
+ s.getCell(3, i).getContents());
}
} else if (s.getCell(2, i).getContents().contains("chkbox")) {
if (selenium
.isElementPresent(s.getCell(0, i).getContents())) {
selenium.click(s.getCell(0, i).getContents());
}

} else if (s.getCell(2, i).getContents().contains("Radio")) {
if (selenium
.isElementPresent(s.getCell(0, i).getContents())) {
selenium.click(s.getCell(0, i).getContents());
}

}
else if (s.getCell(2, i).getContents().contains("Button")) {
if (selenium
.isElementPresent(s.getCell(0, i).getContents())) {
selenium.click(s.getCell(0, i).getContents());
}
}
}

}

return "pass";
}

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
gmail();
Register();

}

}

7. Keys Events

import java.awt.event.KeyEvent;
public class KeyEvents extends DriverScript{
public static void main(String[] args) {
// TODO Auto-generated method stub
selenium.start();
selenium.open("http://www.google.com");
selenium.windowMaximize();
selenium.setCursorPosition("q", "1");
selenium.keyDownNative(Integer.toString(KeyEvent.VK_SHIFT));
selenium.keyPressNative(String.valueOf(KeyEvent.VK_D));
selenium.keyUpNative(Integer.toString(KeyEvent.VK_SHIFT));
//selenium.keyDownNative(Integer.toString(KeyEvent.VK_SHIFT));
selenium.keyPressNative(Integer.toString(KeyEvent.VK_SEMICOLON));
selenium.keyUpNative(Integer.toString(KeyEvent.VK_SHIFT));
selenium.keyPressNative(Integer.toString(KeyEvent.VK_SLASH));
selenium.keyPressNative(String.valueOf(KeyEvent.VK_S));
selenium.keyPressNative(String.valueOf(KeyEvent.VK_E));
selenium.keyPressNative(String.valueOf(KeyEvent.VK_L));
selenium.keyPressNative(String.valueOf(KeyEvent.VK_E));
selenium.keyPressNative(String.valueOf(KeyEvent.VK_N));

}

}

8. Get Data

import com.thoughtworks.selenium.DefaultSelenium;


public class GetData {

public static DefaultSelenium selenium=new DefaultSelenium("localhost",6666,"*iehta","http://");
public static String Bodytext()
{
selenium.start();
selenium.open("http://google.com");
selenium.windowMaximize();
selenium.type("q", "abc");
String str=selenium.getBodyText();
//String str=selenium.getHtmlSource();
String link[]=selenium.getAllWindowNames();

System.out.println("The links are"+link.length);
System.out.println("The links are"+link[0]);

selenium.captureScreenshot("D:\\Selenium\\page.jpg");
return "pass";
}
public static String Dynamic()
{
selenium.click("add1");
String windname[]=selenium.getAllWindowNames();
String windid[]=selenium.getAllWindowIds();
String windtitle[]=selenium.getAllWindowTitles();
selenium.getValue("");

System.out.println("The window names are"+windname.length);
selenium.selectWindow(windname[1]);
selenium.click("ok");

return "pass";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Bodytext();
}

}

9. EXCEL Login

import java.io.FileInputStream;
import java.io.FileOutputStream;

import com.thoughtworks.selenium.DefaultSelenium;

import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class Export_Login {
public static String status = "pass";
public static String export() throws Exception {
FileInputStream file = new FileInputStream(
"D:\\Framework\\TestData\\login_Data.xls");
Workbook w = Workbook.getWorkbook(file);
Sheet s = w.getSheet(0);
FileOutputStream fo = new FileOutputStream(
"D:\\Framework\\Results\\Loginout.xls");
WritableWorkbook wwb = Workbook.createWorkbook(fo);
WritableSheet ws = wwb.createSheet("login", 0);
String a[][] = new String[s.getRows()][s.getColumns()];
DefaultSelenium selenium = new DefaultSelenium("localhost", 6666,
"*iehta", "http://");
selenium.start();
selenium.open("http://mail.in.com");
selenium.windowMaximize();

for (int i = 0; i < s.getRows(); i++) {
selenium.type("f_id", s.getCell(0, i).getContents());
selenium.type("f_pwd", s.getCell(1, i).getContents());
selenium.click("//input[@value='' and @type='submit']");
Thread.sleep(10000);
if (selenium.isElementPresent("link=Sign out")) {
selenium.click("link=Sign out");
Thread.sleep(6000);
status = "Pass";
System.out.println("if loop" + status);
} else {
status = "Fail";
System.out.println("else loop" + status);
}
for (int j = 0; j < s.getColumns(); j++) {

a[i][j] = s.getCell(j, i).getContents();
Label l = new Label(j, i, a[i][j]);
Label Res = new Label(2, 0, "Result");
Label rs = new Label(2, i, status);
ws.addCell(l);
ws.addCell(Res);
ws.addCell(rs);
System.out.println("The contents are" + a[i][j]);
}
selenium.open("http://mail.in.com");
}
wwb.write();
wwb.close();
return "pass";
}

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub

export();
}

}
10.EXCEL

import java.io.FileOutputStream;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class Export_Excel {
public static String export() throws Exception
{
FileOutputStream fo=new FileOutputStream("D:\\Framework\\Results\\Result_export.xls");
WritableWorkbook wwb=Workbook.createWorkbook(fo);
WritableSheet ws=wwb.createSheet("Res", 0);
Label l=new Label(1,0,"Nagesh");
Label l1=new Label(0,0,"Rao");
Label l2=new Label(2,3,"Duplicate");
Label l3=new Label(0,0,"Minq");
ws.addCell(l);
ws.addCell(l1);
ws.addCell(l2);
wwb.write();
wwb.close();

return "pass";
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
export() ;

}

}

11. Execute Test Case


public class Execute_Testcases {
public static void main(String[] args) throws Exception
{
DriverScript.Set_Execution_sheet("D:\\Framework\\Environment\\url.xls");
DriverScript.Execute("D:\\Framework\\MainScript\\testcases.xls");

}

}

12. EXcel

import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
import com.thoughtworks.selenium.DefaultSelenium;
public class Excel extends DriverScript{
public static String login_Excel() throws Exception
{
//DefaultSelenium selenium=new DefaultSelenium("localhost",6666,"*iehta","http://");
FileInputStream file=new FileInputStream("D:\\Framework\\TestData\\login_Data.xls");
Workbook w=Workbook.getWorkbook(file);
Sheet s=w.getSheet(0);
FileInputStream fi=new FileInputStream("D:\\Framework\\ObjectRepository\\login_OR.xls");
Workbook w1=Workbook.getWorkbook(fi);
Sheet s1=w1.getSheet(0);
//Sheet s=w.getSheet("Sheet1");
/*selenium.start();
selenium.open("http://mail.in.com");
selenium.windowMaximize();
*/
// for (int i = 1; i < s.getRows(); i++) {

selenium.type(s1.getCell(0, 1).getContents(), s.getCell(0, 1).getContents());
selenium.type(s1.getCell(1, 1).getContents(), s.getCell(1, 1).getContents());
//System.out.println("the value of i"+i);
//}

// selenium.setTimeout("100000");
selenium.click(s1.getCell(2, 1).getContents());

return "pass";
}
public static String close()
{
selenium.close();
return "pass";
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//login_Excel();

}

}

13. Driver Script

import java.io.FileInputStream;
import java.lang.reflect.Method;

import com.thoughtworks.selenium.DefaultSelenium;

import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class DriverScript{
static String className = null;
public static String urlpath=null;
public static int rs=1;
public static String result=null;
public static DefaultSelenium selenium=new
DefaultSelenium("localhost",6666,"*iehta","http://");
public static boolean Set_Execution_sheet(String strPath) throws Exception
{
String urlpath=strPath;
FileInputStream file= new FileInputStream(urlpath);
Workbook wb=Workbook.getWorkbook(file);
Sheet sh=wb.getSheet(0);
selenium.start();
selenium.open(sh.getCell(1, 1).getContents());
selenium.windowMaximize();
return true;
}
public static boolean Execute(String str) throws Exception
{
FileInputStream file=new FileInputStream(str);
Workbook wb=Workbook.getWorkbook(file);
Sheet s=wb.getSheet(0);
for(int iRownum=1;iRownum<=s.getRows();iRownum++)
{
String ScreenShotPath="D:\\Framework\\Results\\"+"screenshot"+rs +".jpg";
try
{
if(!(s.getCell(5, iRownum).getContents()).contentEquals(""))
{
className=s.getCell(5, iRownum).getContents();
}
else{
for(int i=iRownum;i>1;i--)
{
if(!(s.getCell(5, i).getContents()).contentEquals(""))
{
className=s.getCell(5, i).getContents();
break;
}
}
}
String functioncall = s.getCell(6, iRownum).getContents();
int inumofparameters=0;
Object ret = null;
String methodName = functioncall.substring(0,functioncall.indexOf("("));
String strparameters =
functioncall.substring(functioncall.indexOf("(")+1,functioncall.indexOf(")"));
String strparameterslist[]=strparameters.split(",");
inumofparameters= strparameterslist.length;
selenium.captureScreenshot(ScreenShotPath);
if(strparameters.length()==0){
inumofparameters=0;
}
Class c = Class.forName(className);
if(inumofparameters!=0){
Class cParameters[]=new Class[inumofparameters];
for(int temp=0;temp<inumofparameters;temp++)
{
cParameters[temp]= String.class;
}
Method m = c.getMethod(methodName,cParameters );
Object ob = c.newInstance();
Object arglist[] = new Object[inumofparameters];
for(int iparameternum=0;iparameternum<inumofparameters;iparameternum++)
{
arglist[iparameternum] = new String(strparameterslist[iparameternum]);
}
ret = m.invoke(ob,arglist);
}else
{
Method m = c.getMethod(methodName,null);
Object ob = c.newInstance();
ret = m.invoke(ob,null);
System.out.println("return value:"+ ret);
}
rs++;
}catch(Exception e){
selenium.captureScreenshot(ScreenShotPath);
e.printStackTrace();
}
}

return true;

}
}

14. DOM


public class DOM extends DriverScript{
public static String click(String str)
{
String index=selenium.getEval("var
x=selenium.browserbot.getCurrentWindow().document.getElementsByTagName(\"a\");for(var
i=0;i<x.length;i++){if(x[i].innerHTML.trim()=='"+str+"')i*1;}");
selenium.getEval("var
x=selenium.browserbot.getCurrentWindow().document.getElementsByTagName(\"a\");x["+ index +
"].click();");
return "pass";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
selenium.start();
selenium.open("http://www.google.com");
selenium.windowMaximize();
click("Hindi");

}

}

15. Current Time

import java.util.*;

public class CurrentTime{
public static void main(String[] args){
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
System.out.println("Current Time : " + hour + ":"
+ minute + ":" + second + " " + am_pm);
}
}

16. Create Excel

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class Create_Excel {
public static String dateNow=null;
public static void time()
{
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter=
new SimpleDateFormat("yyyyMMMdd_HHmmss");
dateNow = formatter.format(currentDate.getTime());
System.out.println("Now the date is :=> " + dateNow);
}
public static String excel() throws Exception
{
time();
FileOutputStream fo=new
FileOutputStream("E:\\Framework\\Results\\loginRes_"+dateNow+".xls");
WritableWorkbook wwb=Workbook.createWorkbook(fo);
WritableSheet ws=wwb.createSheet("LoginResults", 0);
Label l=new Label(0,0,"Username");
Label l1=new Label(1,0,"Password");
Label l2=new Label(2,0,"Results");
ws.addCell(l);
ws.addCell(l1);
ws.addCell(l2);
wwb.write();
wwb.close();
return "Pass";
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
excel();
}

}

17. Create Excel 1

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class Create_Excel1 {
public static String dateNow=null;
public static void time()
{
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter=
new SimpleDateFormat("yyyyMMMdd_HHmmss");
dateNow = formatter.format(currentDate.getTime());
System.out.println("Now the date is :=> " + dateNow);

}
public static String excel() throws Exception
{
time();
FileOutputStream fo=new FileOutputStream("E:\\Framework\\Results\\loginres"+dateNow+".xls");
WritableWorkbook wwb=Workbook.createWorkbook(fo);
WritableSheet ws=wwb.createSheet("LoginResults", 0);
Label lab=new Label(0,0,"Username");
Label pw=new Label(1,0,"Password");
Label rs=new Label(2,0,"Result");
ws.addCell(lab);
ws.addCell(pw);
ws.addCell(rs);
wwb.write();
wwb.close();
return "Pass";
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub

excel();

}

}

18. Data Base Script

public class DataBaseTest {

/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
Connection connection = null;
ResultSet objResultSet=null;
PreparedStatement objPreStmnt=null;
try {
DriverManager.registerDriver(new com.microsoft.jdbc.sqlserver.SQLServerDriver());
String
url="jdbc:microsoft:sqlserver://psdbs01\\psdbs01A:1717;DatabaseName=ARROW_0_4_5_0";
connection=DriverManager.getConnection(url,"arrow_sqa","arrow_sqa");
System.out.println(">>>>>>>>>Connected>>>>>>>>");

String strQuery = "select case_id,workitemid,userid from workbasket where case_id=? and
workitemid=? and userid=?";

//Assigning the Query
objPreStmnt = connection.prepareStatement(strQuery);
objPreStmnt.setInt(1,2026086);
objPreStmnt.setInt(2,2000093);
objPreStmnt.setInt(3,2000297);
objResultSet = objPreStmnt.executeQuery(); //Executing the Query
while (objResultSet.next()) {
System.out.println(" case_id:"+objResultSet.getString("case_id"));
System.out.println(" workitemid:"+objResultSet.getString("workitemid"));
System.out.println(" userid:"+objResultSet.getString("userid"));
}

} catch (Exception e) {
e.printStackTrace();
}finally{
objResultSet.close();
objPreStmnt.close();
connection.close();
}

}


}


19. Driver Script


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import com.thoughtworks.selenium.DefaultSelenium;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class DriverScript {
static String className = null;
public static int rs = 1;
public static DefaultSelenium selenium = new DefaultSelenium("localhost",1212,"*firefox",
"http://");
public static boolean Set_Execution_sheet(String strPath) throws Exception {
FileInputStream file = new FileInputStream(strPath);
Workbook wb = Workbook.getWorkbook(file);
Sheet sh = wb.getSheet(0);
selenium.start();
selenium.open(sh.getCell(1, 1).getContents());
selenium.windowMaximize();
return true;
}
public static boolean Execute(String str) throws Exception {
//To take the data from Testcases.xls
FileInputStream file = new FileInputStream(str);
Workbook wb = Workbook.getWorkbook(file);
Sheet s = wb.getSheet(0);
//To create the out put Result file
FileOutputStream fo=new
FileOutputStream("E:\\Framework\\Results\\loginResults.xls");
WritableWorkbook wwb=Workbook.createWorkbook(fo);
WritableSheet ws=wwb.createSheet("LoginResults", 0);
//Add a label 'Result'
Label res=new Label(8,0,"Results");
ws.addCell(res);
//To take each row data
for (int i = 1; i <= s.getRows(); i++) {
try {
if(s.getCell(7, i).getContents().equalsIgnoreCase("Yes"))
{
//Taking the class name from 5,i
if (!(s.getCell(5, i).getContents()).contentEquals("")) {
className = s.getCell(5, i).getContents();
}
//Taking the method name from 6,i
String functioncall = s.getCell(6, i).getContents();
// object declaration
Object ret = "Fail";
//Reading the method name which is available in functioncall string
String methodName = functioncall.substring(0, functioncall.indexOf("("));
//Converting the classname
Class c = Class.forName(className);
//Taking the method name from the class
Method m = c.getMethod(methodName, null);
//Creating the instance
Object ob = c.newInstance();
//Executing the method
ret = m.invoke(ob, null);

System.out.println("return value:" + ret.toString());
//Capturing screen shot
selenium.captureScreenshot("E:\\Framework\\Results\\Result" + rs +
".jpg");
rs++;
for (int j = 0; j < s.getColumns(); j++) {
System.out.println(s.getCell(j, i).getContents());
Label data=new Label(j,i,s.getCell(j, i).getContents());
ws.addCell(data);
}

}
} catch (Exception e) {
selenium.captureScreenshot("E:\\Framework\\Results\\Result"+ rs + ".jpg");
}
}
wwb.write();
wwb.close();
return true;

}
}

20. Export Input Data

import java.io.FileInputStream;
import java.io.FileOutputStream;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class ExportInputdata_Step2 {
public static String export() throws Exception
{
FileInputStream fi=new FileInputStream("E:\\Framework\\Testdata\\logindata.xls");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
FileOutputStream fo=new FileOutputStream("E:\\Framework\\Results\\loginResults.xls");
WritableWorkbook wwb=Workbook.createWorkbook(fo);
WritableSheet ws=wwb.createSheet("LoginResults", 0);
for (int i = 0; i < s.getRows(); i++) {
for (int j = 0; j < s.getColumns(); j++) {
System.out.println(s.getCell(j, i).getContents());
Label data=new Label(j,i,s.getCell(j, i).getContents());
ws.addCell(data);
}
}
Label res=new Label(2,0,"Results");
ws.addCell(res);
wwb.write();
wwb.close();
return "Pass";
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
export();
}

}

21. google Link1

import com.thoughtworks.selenium.DefaultSelenium;
public class Google_link1 {
public static DefaultSelenium selenium;
public static String str=null;
public static void wait(String str) throws Exception
{
for (int i = 0; i < 30; i++) {
if(selenium.isElementPresent(str))
{
Thread.sleep(1000);
selenium.isVisible(str);
break;
}
}
}
public static String openURL()
{
selenium=new DefaultSelenium("localhost",1213,str,"http://");
selenium.start();
selenium.setTimeout("1000000");
selenium.open("http://www.google.co.in/");
selenium.windowMaximize();

return "Pass";
}
public static String hindi() throws Exception
{
try{
selenium.click("link=Hindi");
wait("link=English");
selenium.click("link=English");
Thread.sleep(6000);
}catch(Exception e){e.printStackTrace();}

return "Pass";
}
public static String bengali() throws Exception
{
selenium.click("link=Bengali");
Thread.sleep(6000);
selenium.click("link=English");
Thread.sleep(6000);
return "Pass";
}
public static String telugu() throws Exception
{
selenium.click("link=Telugu");
Thread.sleep(6000);
selenium.click("link=English");
Thread.sleep(6000);
return "Pass";
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
str="*firefox";
for (int i = 0; i < 2; i++) {
openURL();
hindi();
bengali();
telugu();
}
}



}
22. Google Link2

import com.thoughtworks.selenium.DefaultSelenium;
public class Google_link2 {
private static DefaultSelenium selenium=new
DefaultSelenium("localhost",1212,"*firefox","http://");
public static String openURL()
{
selenium.start();
selenium.open("http://www.google.co.in/");
selenium.windowMaximize();
return "Pass";
}
public static String Click_link(String str) throws Exception
{
selenium.click("link="+str);
Thread.sleep(6000);
selenium.click("link=English");
Thread.sleep(6000);
return "Pass";
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
openURL();
Click_link("Hindi");
Click_link("Bengali");
Click_link("Telugu");
}

}

23. Google Search

import com.thoughtworks.selenium.DefaultSelenium;


public class GooglesSearch extends DriverScript{

public static String gs()
{
//DefaultSelenium selenium=new DefaultSelenium("localhost",1212,"*firefox","http://");
//selenium.start();
//selenium.open("http://google.co.in");
//selenium.windowMaximize();
selenium.type("gbqfq", "Nagesh");
selenium.click("gbqfb");

return "Pass";
}



}

24. JUNIT

import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class Junit extends SeleneseTestCase {
@Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 1212, "*chrome", "http://www.mail.in.com/");
selenium.start();
}

@Test
public void testUntitled() throws Exception {
selenium.open("/");
selenium.windowMaximize();
selenium.click("css=input.registernowjgfjvku");
selenium.waitForPageToLoad("30000");
selenium.type("id=fname", "nagesh");
selenium.select("id=day", "label=13");
selenium.select("id=month", "label=Mar");
selenium.select("id=year", "label=2000");
selenium.type("id=username", "nagesh_2000");
}

@After
public void tearDown() throws Exception {
selenium.stop();
}
}

25. Login_OR_TD
import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
import com.thoughtworks.selenium.DefaultSelenium;
public class Login_OR_TD {
public static DefaultSelenium selenium=new DefaultSelenium("localhost",1212,"*firefox","http://");
public static String openURL()
{
selenium.start();
selenium.open("http://www.mail.in.com/");
selenium.windowMaximize();
return "Pass";
}
public static String login() throws Exception
{
FileInputStream fi=new FileInputStream("E:\\Framework\\Testdata\\logindata.xls");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
FileInputStream fi1=new FileInputStream("E:\\Framework\\Object Repository\\loginOR.xls");
Workbook w1=Workbook.getWorkbook(fi1);
Sheet s1=w1.getSheet("Sheet1");
selenium.type(s1.getCell(0, 1).getContents(), s.getCell(0, 1).getContents());
selenium.type(s1.getCell(1, 1).getContents(), s.getCell(1, 1).getContents());
selenium.click(s1.getCell(2, 1).getContents());
selenium.waitForPageToLoad("30000");
return "Pass";
}
public static String logout()
{

selenium.click("link=");
return "Pass";

}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
openURL();
login();
logout();


}

}

26. Login Results

import java.io.FileInputStream;
import java.io.FileOutputStream;
import com.thoughtworks.selenium.DefaultSelenium;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class Login_Results_Step3 {
public static DefaultSelenium selenium=new DefaultSelenium("localhost",1212,"*firefox","http://");
public static String login() throws Exception
{
//To take data from Input file
FileInputStream fi=new FileInputStream("E:\\Framework\\Testdata\\logindata.xls");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
//To create the out put Result file
FileOutputStream fo=new FileOutputStream("E:\\Framework\\Results\\loginResults.xls");
WritableWorkbook wwb=Workbook.createWorkbook(fo);
WritableSheet ws=wwb.createSheet("LoginResults", 0);
//String declaration
String str=null;
//Launching the application
selenium.start();
selenium.open("http://www.mail.in.com/");
selenium.windowMaximize();

for (int i = 1; i < s.getRows(); i++) {
//To login into the application by taking data from xls
selenium.type("f_id", s.getCell(0, i).getContents());
selenium.type("f_pwd", s.getCell(1, i).getContents());
selenium.click("css=input.signin");
selenium.waitForPageToLoad("30000");
//Validating the Sign out link
if(selenium.isElementPresent("link=Sign out"))
{
selenium.click("link=Sign out");
Thread.sleep(3000);
str="Pass";
}else{
str="Fail";
System.out.println("Sign out is not available");
}
// To get the home page
selenium.open("http://www.mail.in.com/");
//Export the result into Result file
Label result=new Label(2,i,str);
ws.addCell(result);
// To export input data into Result file
for (int j = 0; j < s.getColumns(); j++) {
System.out.println(s.getCell(j, i).getContents());
Label data=new Label(j,i,s.getCell(j, i).getContents());
ws.addCell(data);
}
}
// Adding labels in the Result file
Label un=new Label(0,0,"Username");
Label pw=new Label(1,0,"Password");
Label res=new Label(2,0,"Results");
ws.addCell(un);
ws.addCell(pw);
ws.addCell(res);
wwb.write();
wwb.close();
return "Pass";
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
login();
}

}

27. Login ReTesting

import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
import com.thoughtworks.selenium.DefaultSelenium;
public class Login_Retesting {
public static DefaultSelenium selenium=new DefaultSelenium("localhost",1212,"*firefox","http://");
public static String openURL()
{
selenium.start();
selenium.open("http://www.mail.in.com/");
selenium.windowMaximize();
return "Pass";
}
public static String login() throws Exception
{
FileInputStream fi=new FileInputStream("E:\\Framework\\Testdata\\logindata.xls");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
FileInputStream fi1=new FileInputStream("E:\\Framework\\Object Repository\\loginOR.xls");
Workbook w1=Workbook.getWorkbook(fi1);
Sheet s1=w1.getSheet("Sheet1");
for (int i = 1; i < s.getRows(); i++) {
selenium.type(s1.getCell(0, 1).getContents(), s.getCell(0, i).getContents());
Thread.sleep(1000);
selenium.type(s1.getCell(1, 1).getContents(), s.getCell(1, i).getContents());
}

//selenium.click(s1.getCell(2, 1).getContents());
//selenium.waitForPageToLoad("30000");
return "Pass";
}
public static String logout()
{

selenium.click("link=");
return "Pass";

}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
openURL();
login();
//logout();


}

}

28. Mail Login


public class Mail_Login extends DriverScript{
//public static DefaultSelenium selenium=new
DefaultSelenium("localhost",1212,"*firefox","http://");
public static String openURL()
{
/*selenium.start();
selenium.open("http://www.mail.in.com/");
selenium.windowMaximize();*/
return "Pass";
}
public static String login()
{
selenium.type("f_id", "mar1selenium");
selenium.type("f_pwd", "selenium");
selenium.click("css=input.signin");
selenium.waitForPageToLoad("30000");
return "Pass";
}
public static String logout()
{
if(selenium.isElementPresent("link=Sign out"))
{
selenium.click("link=Sign out");
System.out.println("Pass");
}else{
System.out.println("Fail");
}

return "Pass";

}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub


}

}

29. Mail Reg

public class Mail_Reg extends Mail_Login{

public static String reg() throws Exception
{
selenium.click("css=input.registernow");
selenium.waitForPageToLoad("30000");
selenium.type("fname", "Nagesh");
selenium.select("day", "5");
selenium.select("month", "Apr");
selenium.select("id=year", "label=2001");
selenium.type("id=username", "nagesh2001");
selenium.type("id=password", "nagesh123");
selenium.type("id=repassword", "nagesh123");
selenium.type("id=altemail", "nag@gmail.com");
selenium.click("id=imageField");
Thread.sleep(2000);
selenium.click("id=imageField");
selenium.select("mcountry", "India");


return "Pass";
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
openURL();
reg();
}

}


30. Spice Jet popup

import com.thoughtworks.selenium.DefaultSelenium;


public class Spicejet_Popup {
public static DefaultSelenium selenium=new
DefaultSelenium("localhost",1234,"*firefox","http://");
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
selenium.start();
selenium.open("http://spicejet.com");
selenium.windowMaximize();
selenium.click("id=oneWayRadio");
selenium.select("id=from1Select", "label=Hyderabad");
selenium.select("id=to1Select", "label=Vizag");
selenium.click("css=#to1Select > option[value=\"VTZ\"]");
selenium.click("id=departDate1text");
selenium.click("link=5");
selenium.click("id=submitBtn");
selenium.getConfirmation();
Thread.sleep(10000);
selenium.click("id=m1f1r1");
selenium.click("id=converterButton");
selenium.waitForPopUp("converter", "30000");
selenium.selectWindow("name=converter");
selenium.type("id=amountText", "100");
selenium.select("name=convert_from", "label=US Dollar (USD)");
selenium.select("name=convert_to", "label=Indian Rupee (INR)");
Thread.sleep(2000);
selenium.click("id=closeButton");
Thread.sleep(2000);
//selenium.waitForPageToLoad("30000");
selenium.selectWindow("null");
selenium.click("id=nextDayButton1");
selenium.waitForPageToLoad("30000");

}

}

31. Step 2
import java.io.FileInputStream;
import java.io.FileOutputStream;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class Step2 {
public static String export() throws Exception
{
FileInputStream fi=new
FileInputStream("E:\\Framework\\Testdata\\logindata.xls");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
FileOutputStream fo=new
FileOutputStream("E:\\Framework\\Results\\loginresults.xls");
WritableWorkbook wwb=Workbook.createWorkbook(fo);
WritableSheet ws=wwb.createSheet("LoginResults", 0);
for (int i = 0; i < s.getRows(); i++) {
for (int j = 0; j < s.getColumns(); j++) {
System.out.println(s.getCell(j, i).getContents());
Label lab=new Label(j,i,s.getCell(j, i).getContents());
ws.addCell(lab);
}
}
Label rs=new Label(2,0,"Results");
ws.addCell(rs);
wwb.write();
wwb.close();
return "Pass";
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
export();
}

}

32. Time

import java.util.Calendar;
import java.text.SimpleDateFormat;

public class Time {
public static void main(String arg[]) {
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter=
new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
System.out.println("Now the date is :=> " + dateNow);
}
}

-----------------------------------------------------------------------------------------
Java Interview Questions: 10 Common Questions and How
To Answer Them


The typical company hiring a Java programmer is looking for someone who can
program well beyond the level taught in an introductory Java class. Interviewers
ask questions that arent necessarily stumpers but are meant to elicit a
candidates deeper knowledge of the subject matter.

The questions below are examples of what a Java programmer can expect in a
technical interview.
1. WHAT DOES THE STATIC KEYWORD
MEAN, AND WHERE CAN IT BE USED?
static can be used in four ways:
static variables are shared by the entire class, not a specific instance
(unlike normal member variables)
static methods are also shared by the entire class
static classes are inner classes that arent tied to their enclosing
classes
static can be used around a block of code in a class to specify code
that runs when the virtual machine is first started up, before instances of
the class are created.
2. HOW DO YOU DEAL WITH
DEPENDENCY ISSUES?
This question is purposely ambiguous. It can refer to solving the dependency
injection problem (Guice is a standard tool to help). It can also refer to project
dependencies using external, third-party libraries. Tools like Maven and
Gradle help manage them. You should consider learning more about Maven as a
way to prepare for this question.
3. YOU WANT TO CREATE A SIMPLE
CLASS THAT JUST HAS THREE MEMBER
VARIABLES. TELL ME HOW YOUD DO
THIS.
This problem seems simple at first, and creating such a simple class is covered
in classes like Programming Java for Beginners.
But an experienced programmer will recognize that its necessary to know how to
correctly override the hashCode() and equals() methods (using, for example,
EqualsBuilder and HashCodeBuilder, in the Apache Commons library).
4. WHAT DOES SYNCHRONIZED DO? TELL ME HOW
TO USE IT TO SET A VARIABLE JUST
ONE WITHOUT ANY RACE CONDITIONS?
synchronized says that a method has to hold the objects lock to execute. If used
around a block, like synchronized (obj) { ... } , it will grab the lock of obj before
executing that block. Classes like Programming Java for Beginners and Java
Fundamentals I and II will provide a refresher.
5. WHAT IS TYPE ERASURE?
Type erasure is a JVM phenomenon that means that the runtime has no
knowledge of the types of generic objects, like List<Integer> (the runtime sees
all List objects as having the same type, List<Object> ). The topic of type erasure
is covered in Advanced Java Programming.
6. WHEN AND WHY ARE GETTERS AND
SETTERS IMPORTANT?
While an advanced Java class covers the topic, the key factor to
know for interviews is that setters and getters can be putin interfaces and can
hide implementation details, so that you dont have to make member variables
public (which makes your class dangerously brittle).
7. WHAT ARE THE DIFFERENCES
BETWEEN MAP, HASHTABLE, HASHMAP,
TREEMAP, CONCURRENTHASHMAP,
LINKEDHASHMAP?
Map is an interface for a key-value map
HashMap is a Map that uses a hash table for its implementation
Hashtable is a synchronized version of HashMap
TreeMap uses a tree to implement a map
ConcurrentHashMap allows for multiple threads to access it at the
same time safely
LinkedHashMap preserves the iteration order that things were
inserted in (others dont provide a fixed iteration order)
A deeper discussion of the differences can be found in Advanced Java
Programming.
8. WHAT ARE THE DIFFERENCES
BETWEEN INTERFACES, ABSTRACT
CLASSES, CLASSES, AND INSTANCES?
Interfaces are essentially a list of methods that implementations
must possess, but have no code or member variables
Abstract classes cannot be instantiated, but can contain variables,
implemented methods, and unimplemented methods
Classes contain variables and implemented methods only, and can
be instantiated
Instances (or objects) are specific examples of a particular class.
9. IF YOU NEEDED TO PROVIDE A GUI
FOR YOUR JAVA PROGRAM, HOW
WOULD YOU GO ABOUT IT?
There are a lot of options, from web apps to local applications. Usually,
interviewers mean Swing or other GUI toolkits with a question like this. It may be
worth going through a course on Java Swing Programming before an interview.
10. HOW DO YOU TEST YOUR CODE?
You should talk about your experience using libraries like JUnit, Mockito, and
Selenium. Even if you dont have extensive knowledge about testing, being able
to talk about the libraries is a good first step.
Test-Driven-Development (TDD) is very popular these days, and any experience
here would also be good to talk about. There are courses on Test Driven
Development in Java which can bring you up to speed.


----------------------------------------------------------------------------------------
WHAT IS MEANT BY SCRUM AND SPRINT
Scrum is an iterative and incremental Agile software development framework for managing software projects
and product or application development. Its focus is on "a flexible, holistic product development strategy where
a development team works as a unit to reach a common goal" as opposed to a "traditional, sequential
approach". Scrum enables the creation of self-organizing teams by encouraging co-location of all team
members, and verbal communication among all team members and disciplines in the project.
A key principle of Scrum is its recognition that during a project the customers can change their minds about
what they want and need (often called requirements churn), and that unpredicted challenges cannot be easily
addressed in a traditional predictive or planned manner. As such, Scrum adopts an empirical approach
accepting that the problem cannot be fully understood or defined, focusing instead on maximizing the team's
ability to deliver quickly and respond to emerging requirements.

----------------------------------------------------------------------------------------
Selenium Testing Concepts

Introduction
What is automation testing
When best to go for automation
Advantages of Automation
Criteria for Automation
Introduction to Selenium
What is Selenium
Use of selenium
When selenium can be useful in testing
Features of Selenium
Differences between Selenium
and QTP
Selenium Components
Selenium IDE
Selenium RC
Selenium Webdriver
Selenium Grid
Configuration of IDE & Dev Scripts
Recording the script
Running the script
script
Object Identification
Difference between Test case and
test suit
Languages supported while
Recording
Synchronization in Selenium IDE
Testing Vs Selenium IDE
When to use Selenium IDE
How to run the recorded script
Against other browsers
Why companies are not using
Recording tools
Creating the Environment for
Selenium RC
Creating generic scripts in
Selenium
Creating scripts by using
Functions
Running the scripts in Eclipse
Inheritance
Browser commands with examples
Interactive commands with examples
Information commands with examples
Validation commands with examples
How to take data from excel sheets
Why should we use excel sheets
How to take large no of data from excel sheets
How to export data to an excel sheets
Export large no of data to an excel sheet
How to export results after completion of execution the script
How to use Eclipse
Debugging the script
Maintaining synchronization Points
How to handle Pop ups and alert messages
Recognizing Similar Elements
Working with Table Elements
Connecting to Database
Developing reusable script
Validations
What is validation
What is the use of validation in
Automation testing
When to use validation in real time
How to use validations
Core Java Fundamentals
Language Fundamentals
Java Programming Language Keywords
Class and Object
Data Types
Array Declaration, Construction and
Initialization
Flow Control, Exceptions, and
Assertions
Writing Code Using If and Switch
Statements
Writing Code using Loops
Handling Exceptions
Working with the Assertion Mechanism
Object Orientation, Overloading and
Overriding, Constructors
Benefits of Encapsulation
Overridden and Overloaded Methods
Using the java.lang.String Class
Using the java.lang.Math Class
Using Wrapper Classes
Using the equals() Method with
Strings, Wrappers and Objects
Defining, Instantiating, and
Starting
Threads
Preventing Thread Execution
Synchronizing Code
Thread Interaction
JUnit Introduction
Proving it works
Starting from scratch
Understanding unit testing
Frameworks
Setting up JUnit
Testing with JUnit
Object repository
What is object repository
How to use object repository in
Framework
What is the use of maintain
Object repository
Types of creating object repository
Additional concepts
How to use XPath
How to use DOM
How to use Key Commands
Selenium 2 / Web Driver
Selenium 2.0 Features
The Selenium Server When to Use it
Setting up a Selenium Web
Driver Project
Migrating from Selenium 1.0
Getting Started with Selenium
Web Driver
Introducing Web Drivers Drivers
Commands & Operation
Web Driver backed Selenium RC
Programs on Web Driver
Programs on Web Driver Backed
Selenium RC
TestNG Framework
What is TestNG
Create TestNG.xml file
Integrate the Selenium Scripts
and Run from TestNG
Reporting Results & Analyze
Run Scripts from Multiple
Browsers
Automation Life Cycle
What is a Framework?
Types of Frameworks
Modular framework
Data Driven framework
Keyword driven framework
Hybrid framework
Use of Framework
How develop the framework
Integration of the framework
How execute the scripts from Framework


----------------------------------------------------------------------------------------
BASIC QUESTIONS ON SELENIUM
WHAT IS JAR?
JAR stands for Java ARchive. It's a file format based on the popular ZIP file
format and is used for aggregating many files into one. Although JAR can be
used as a general archiving tool, the primary motivation for its development
was so that Java applets and their requisite components (.class files, images
and sounds) can be downloaded to a browser in a single HTTP transaction,
rather than opening a new connection for each piece. This greatly improves the
speed with which an applet can be loaded onto a web page and begin
functioning. The JAR format also supports compression, which reduces the size
of the file and improves download time still further. Additionally, individual
entries in a JAR file may be digitally signed by the applet author to authenticate
their origin.

JAR is:
the only archive format that is cross-platform
the only format that handles audio and image files as well as class files
backward-compatible with existing applet code
an open standard, fully extendable, and written in java
the preferred way to bundle the pieces of a java applet

JAR consists of a zip archive, as defined by PKWARE, containing a manifest file
and potentially signature files, as defined in the JAR File Specification.
What Is a Package?
A package is a namespace that organizes a set of related classes and interfaces.
Conceptually you can think of packages as being similar to different folders on
your computer. You might keep HTML pages in one folder, images in another,
and scripts or applications in yet another. Because software written in the Java
programming language can be composed of hundreds or thousands of individual
classes, it makes sense to keep things organized by placing related classes and
interfaces into packages.
The Java platform provides an enormous class library (a set of packages)
suitable for use in your own applications. This library is known as the
"Application Programming Interface", or "API" for short. Its packages represent
the tasks most commonly associated with general-purpose programming. For
example, a String object contains state and behavior for character strings;
a File object allows a programmer to easily create, delete, inspect, compare, or
modify a file on the filesystem; a Socket object allows for the creation and use
of network sockets; various GUI objects control buttons and checkboxes and
anything else related to graphical user interfaces. There are literally thousands
of classes to choose from. This allows you, the programmer, to focus on the
design of your particular application, rather than the infrastructure required to
make it work.
The Java Platform API Specification contains the complete listing for all
packages, interfaces, classes, fields, and methods supplied by the Java SE
platform. Load the page in your browser and bookmark it. As a programmer, it
will become your single most important piece of reference documentation.

----------------------------------------------------------------------------------------
CORE JAVA FAQS

1. Q. what is an object?

A.object is anything that is really exists.

2. Q. what is a method and class?

A.class is a blue print/ group name /collection of objects. method represents group of
statements that perform a task and it is reusable component.

3. Q. What is the difference between String and Array

A.String it is a collection of characters. Array is a collection of elements which are same
types examples are integer/float/double array ex:int[]a={10,12,3,13};

4. Q. How to split a string

A.By using split() method we can split the string but it returns String array. String[]
str1=str.split(" ")

5. Q. What is Overloading

A.Writing two or more methods in a class in such a way that each method having the same
name with different parameters is called Overloading

6. Q. What is Overriding

A.Writing two or more methods in super class and sub class such a way that each method
has same name and same signatures and same return types.

7. Q. What is Inheritance

A.acquiring(copying) properties and methods from one class to another class.

8. Q. How to Reverse string with out using reverse method

A.
String str="Nagesh";
for (int i = str.length()-1; i >= 0; i--) {
System.out.println(str.charAt(i));
}

----------------------------------------------------------------------------------------
WEB DRIVER SCRIPTS
Capture Screen Shots.

public class CaptureScreenshot {
public WebDriver driver;

public void captureScreenShot(String str) throws Exception{
DateFormat dateFormat = new SimpleDateFormat("yyyy_MMM_dd HH_mm_ss");
Date date = new Date();
String time=dateFormat.format(date);
File f = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(f, new File("D:\\Workspace_Weekend_14Dec\\"+str+time+".jpg"));
}
@Test
public void f() throws Exception{
driver=new FirefoxDriver();
driver.get("http://spicejet.com");
captureScreenShot("Homepage");
driver.findElement(By.linkText("Book a Flight")).click();
captureScreenShot("BookaFlight");
}
}

2. Drop down Validation
package testNG;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;

public class DropdownValidation {
public WebDriver driver;
@Test
public void f() {
/* String s[]=new String[15];
List<String> s1=new ArrayList<String>();*/

driver.get("http://spicejet.com");
driver.findElement(By.linkText("Book a Flight")).click();
String
str="ControlGroupSearchView_AvailabilitySearchInputSearchView_DropDownListPassengerType_
ADT";
List<WebElement> s=new Select(driver.findElement(By.id(str))).getOptions();
System.out.println(s.size());
for (int i = 0; i < s.size(); i++) {
//System.out.println(s.get(i).getText());
if(s.get(i).getText().equalsIgnoreCase("5 Adults"))
{
System.out.println(s.get(i).getText());
new Select(driver.findElement(By.id(str))).selectByVisibleText(s.get(i).getText());
}
}

}
@BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", "D:\\Lib\\chromedriver.exe");
driver=new ChromeDriver();
}

@AfterTest
public void afterTest() {
}

}

3. Mail Login register

package testNG;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;

public class Mail_Login_Register {
public WebDriver driver;
@Test
public void verifyLogin() throws Exception{
driver.get("http://mail.in.com");
driver.findElement(By.id("f_id")).sendKeys("jan30selenium");
driver.findElement(By.id("f_pwd")).sendKeys("selenium");
driver.findElement(By.cssSelector("input.signin")).click();
Thread.sleep(4000);
driver.findElement(By.linkText("Sign out")).click();
}
@Test //Test Scenario
public void verifyRegister() throws Exception{
driver.get("http://mail.in.com");
driver.findElement(By.cssSelector("input.registernow")).click();
driver.findElement(By.id("fname")).sendKeys("Nagesh");
new Select(driver.findElement(By.id("day"))).selectByVisibleText("10");
new Select(driver.findElement(By.id("month"))).selectByVisibleText("Jun");
new Select(driver.findElement(By.id("year"))).selectByVisibleText("1983");
Thread.sleep(1000);
driver.findElement(By.xpath("(//input[@name='radiousername'])[3]")).click();
Thread.sleep(3000);
driver.findElement(By.id("password")).sendKeys("nag123");
driver.findElement(By.id("repassword")).sendKeys("nag123");
driver.findElement(By.id("altemail")).sendKeys("nag@gmail.com");
driver.findElement(By.id("imageField")).click();
Thread.sleep(3000);
driver.findElement(By.xpath("(//input[@id='gender'])[2]")).click();
}
@BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", "D:\\Lib\\chromedriver.exe");
driver=new ChromeDriver();

}

@AfterTest
public void afterTest() {
driver.quit();
}

}

4. Print All links

package testNG;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;

public class PrintAllLinks {
public WebDriver driver;
@Test
public void f() {
/* String s[]=new String[15];
List<String> s1=new ArrayList<String>();*/
driver.get("http://spicejet.com");
List<WebElement> str=driver.findElements(By.tagName("a"));
System.out.println(str.size());
for (int i = 0; i < str.size(); i++) {
System.out.println(str.get(i).getText());//str[i]
}

}
@BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", "D:\\Lib\\chromedriver.exe");
driver=new ChromeDriver();
}

@AfterTest
public void afterTest() {
}

}

5. Spice jet Pop ups

package testNG;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;

public class Spicejet_Popup {
public WebDriver driver;
@Test(description="Verify URL")
public void test1() {
driver.get("http://spicejet.com");
}
@Test(description = "Verify BookAFlight")
public void test2(){
driver.findElement(By.linkText("Book a Flight")).click();
}
@Test(description ="Verify Oneway search")
public void test3() throws Exception{
driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchView_OneWa
y")).click();

driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchVieworiginStati
on1_CTXT")).click();
driver.findElement(By.linkText("Hyderabad (HYD)")).click();
Thread.sleep(1000);
driver.findElement(By.linkText("Bengaluru (BLR)")).click();
Thread.sleep(1000);
driver.findElement(By.linkText("26")).click();
Thread.sleep(1000);
new
Select(driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchView_Dr
opDownListPassengerType_ADT"))).selectByVisibleText("2 Adults");
new
Select(driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchView_Dr
opDownListPassengerType_CHD"))).selectByVisibleText("2 Children");

driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchView_ButtonSu
bmit")).click();
Thread.sleep(1000);
}
@Test(description ="Verify Confirmation Alert")
public void test4(){
String str=driver.switchTo().alert().getText();
System.out.println(str);
driver.switchTo().alert().accept();
//driver.switchTo().alert().dismiss();
}
@Test(description ="Verify popup")
public void test5() throws Exception{
Thread.sleep(4000);
String windowName=driver.getWindowHandle();
driver.findElement(By.linkText("Currency Converter")).click();
driver.switchTo().window("converter");
new
Select(driver.findElement(By.id("CurrencyConverterCurrencyConverterView_DropDownListBaseC
urrency"))).selectByVisibleText("US Dollars(USD)");
new
Select(driver.findElement(By.id("CurrencyConverterCurrencyConverterView_DropDownListConve
rsionCurrency"))).selectByVisibleText("Indian Rupee(INR)");
driver.findElement(By.id("CurrencyConverterCurrencyConverterView_TextBoxAmount")).sendKey
s("100");
Thread.sleep(1000);
//driver.findElement(By.id("ButtonCloseWindow")).click();
driver.close();
driver.switchTo().window(windowName);
new
Select(driver.findElement(By.id("AvailabilitySearchInputSelectViewdestinationStation1"))).selectBy
VisibleText("Bhopal (BHO)");
}

@BeforeTest //Precondition
public void beforeTest() {
System.setProperty("webdriver.ie.driver", "D:\\Lib\\IEDriverServer.exe");
driver=new InternetExplorerDriver();
}

@AfterTest
public void afterTest() {
driver.quit();
}

}

6. Split

package testNG;

import org.testng.annotations.Test;

public class Splits {
@Test
public void f() {
/*String s1[]=new String[9];
int j[]=new int[10];
Object o[]=new Object[12];*/

String str="seven,six,ten,one,two,three,four,five";
String[] s=str.split(",");
System.out.println(s.length);
for (int i = 0; i < s.length; i++) {
// System.out.println(s[i]);
if(s[i].equalsIgnoreCase("three"))
{
System.out.println(s[i]);
}
}



}
}

7. Validation commands

package testNG;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.thoughtworks.selenium.Selenium;

public class ValidationCommands {
public WebDriver driver;
public Selenium selenium;
@Test(enabled=false)
public void f() throws Exception{
driver.get("http://spicejet.com");
driver.findElement(By.linkText("Book a Flight")).click();

driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSear
chView_OneWay")).click();
Thread.sleep(1000);
if(driver.findElement(By.id("custom_date_picker_id_2")).isDisplayed())
{
System.out.println("Available");
}else{
System.out.println("Not available");
}

}
@Test
public void verifyUsername(){
driver.get("http://mail.in.com");
/*if(driver.findElement(By.id("f_id")).isDisplayed()){
System.out.println("Available");
}else{
System.out.println("Not available");
}*/

Assert.assertEquals(selenium.isElementPresent("f_idcv"), true);
Assert.assertEquals(driver.findElement(By.id("f_idcv")).isDisplayed(), true);
if(selenium.isElementPresent("f_iddfg"))
{
System.out.println("Available");
}else{
System.out.println("Not available");
}
}
@BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", "D:\\Lib\\chromedriver.exe");
driver=new ChromeDriver();
selenium=new WebDriverBackedSelenium(driver, "http://mail.in.com");
}
}



----------------------------------------------------------------------------------------
Selenium FAQs
1. Q. Advantages of automation

A.1. It saves time by executing the test cases with out manual effort 2. CTC(Cost to the
company) can be saved 3. We can maintain Accuracy by repeating the same task in same
manner 4. Bugs can be identified 5. We can report the bugs to the developer 6. We can
ensure for quality




2. Q. What are the components available in Selenium

A.Selenium contains 4 components
1. Selenium IDE 2. Selenium RC 3. Selenium WebDriver 4. Selenium Grid




3. Q. Why should we go for Selenium instead of QTP

A.1. Selenium is an opensource tool 2. It supports multiple languages like
Java,C#,Perl,python,Ruby,HTML and PHP 3. It supports Firefox, IE, Google chrome, Safari
and Opera 4. Supports Windows, Linux and Mac 5.Supports Web Applications 6. Its very
flexible and extendable 7. It supports mobile web applications


4. Q. What is Selenium IDE

A.1. IDE stands for integrated Development environment. 2. It is for Record and Run the
Scripts 3. Selenium IDE is an add on for Firefox 4. Its accountable for user actions 5.
Recorded script can be viewed in all the supported languages like HTML, JAVA, C#, Ruby,
Perl, Python 6. Recorded script can be run against other browsers also by using Selenium
RC or Webdriver


5. Q. How to capture screen shot in web driver.

A.We can capture screenshot by using below two lines:

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\screenshot.png"));



6. Q. How to maximize the browser in web driver.

A.driver.manage().window().maximize();


7. Q. How to run selenium server from command prompt.

A.1. Go to command prompt 2. Give the path, Where the selenium server is saved ex: cd
E:Library 3. Use the command "java -jar selenium-server-standalone-2.33.0.jar"


8. Q. What is Selenium RC

A.RC stands for Remote Control. It is a server and it launches browsers. It acts as API and
library. It controls the entire automation


9. Q. How many test cases can be automated per day.

A.It always depends on the application and test cases. But on and average we can automate
5 to 6 test cases per day. Ex: 1. For analyzing the test cases 2. Developing the script 3.
Debugging and executing the script 4. Stabilizing the script


10. Q. What challenges you have faced with Selenium.

A.Challenge means problems or issues 1. Maintaining synchronization is a challenge in
Selenium. 2. Handling Desktop, Flex, Flash elements is challenge with selenium. 3. Proving
the user defined Results a challenge 4. Taking the data from the application is a challenge


11. Q. How to handle SSL Certificate issue in Firefox with Webdriver

A.FirefoxProfile profile = new FirefoxProfile(); profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificateIssuer(false); driver=new FirefoxDriver(profile);


12. Q. What is the latest version of Selenium available

A.selenium-server-standalone-2.37.0.jar


13. Q. What is Automation

A.The process of converting the manual test cases to test scripts by using any automation
tool is known as Automation


14. Q. How to handle SSL certication issue in IE

A.Add the below command after opening the browser.

driver.navigate().to("javascript:document.getElementById('overridelink').click()");


15. Q. How to change the port number for Selenium RC

A.Syntax: -jar seleniumJarfileName -port anyFourdigitNo
Ex: -jar selenium-server-standalone-2.33.0.jar -port 1234


16. Q. How do you start Selenium RC from command prompt?

A.1. Save the selenium jarfile (Selenium-server-standalone-2.34.0.jar) in any folder (Ex:
D:/Library)
2. Open command prompt
3. Navigate to the path where you have saved the jar file and follow the below steps

D:
cd D:/Library
java -jar selenium-server-standalone-2.34.0.jar




17. Q. What locators available in Selenium RC

A.ID
Name
CSS (Cascade style sheet)
XPATH (Relative xpath and Absolute xpath)
Dom






18. Q. What locators available in Selenium Webdriver

A.ID
Name
CSS
XPath
Classname
TagName
LinkText
Partial Link Text


19. Q. How to create DefaultSelenium object and what parameters needs to be
pass

A.DefaultSelenium selenium= new DefaultSelenium("localhost",4444,"*firefox","http://");

localhost - It is the machine name and selenium server should be configured in the specific
machine

4444 - It's selenium port number.

*firefox - Its is the command to launch firefox

http:// - Protocol to open URL



20. Q. How many types of Xpaths are available

A.Xpath is two types:

1. Relative XPath
2. Absolute XPath


21. Q. What is the difference between single and double slash in Xpath.

A."// " is the starting point of the Xpath.
"/" will navigate into the tag

Ex: //html/head/body/div1/div2/......




22. Q. How to handle Alerts and Confirmation Alerts in WebDriver

A.We have to navigate to Alert or Confirmation as below,

driver.switchTo().alert()

To click OK or Cancel on Alert or Confirmation Alert then follow as below

driver.switchTo().alert().accept(); -- To click OK

driver.switchTo().alert().dismiss(); -- To click Cancel




23. Q. How to Handle Popup in Webdriver

A.We have to navigate to the popup as below

driver.switchTo().window("Window Name");

To navigate from Popup to main window

driver.switchTo().window("Main Window Name");



24. Q. How to handle dynamically changing popup in Webdriver

A.Dynamic means the Name is not constant. It changes frequently

Use the below approach to handle Dynamically changing popup

Set<String> s=driver.getWindowHandles();
Object popup[]=s.toArray();
driver.switchTo().window(popup[1].toString());





25. Q. Is it possible to handle multiple popups in Webdriver

A.Yes.
We can handle it by using the command

driver.getWindowHandles();






26. Q. How to capture window name

A.driver.getWindowHandle();



27. Q. How to launch Firefox, Safari and Opera with Webdriver

A.
Firefox, Safari and Opera we be launch by using below commands.
WebDriver driver=new FirefoxDriver();
WebDriver driver=new OperaDriver();
WebDriver driver=new SafariDriver();


28. Q. How to launch InternetExplorer.

A.
For IE, we need the supported "Internet Explorer Driver Server". It can be downloaded from
the below site:
http://docs.seleniumhq.org/download/
Below code is to launch IE.
System.setProperty("webdriver.ie.driver", "E:\\Library\\IEDriverServer.exe");
driver=new InternetExplorerDriver();
driver.get("http://gmail.com");





29. Q. How to launch GoogleChrome

A.
For GoogleChrome, We need the supported "ChromeDriver" exe file. Can be downloaded
from the below site:
http://code.google.com/p/chromedriver/downloads/list
Below code is to launch GoogleChrome
System.setProperty("webdriver.chrome.driver", "E:\\Library\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("http://gmail.com");




30. Q. Brief about the Disadvantages of Selenium

A.Selenium supports Web applications. It doesn't support Desktop applications


31. Q. How to handle Deskptop, Flex and Flash objects in Selenium.

A.
We can use SIKULI as a add-on for Selenium to support Desktop, Flex and Flash objects
Sikuli is an open source automation tool developed on JAVA
Can be downloaded from:https://launchpad.net/sikuli/+download



32. Q. How to take data from excel(xls) file

A.
FileInputStream fi=new FileInputStream("Path of the excel file");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(0);
It will read the excel file upto the sheet. To take the data from sheet, use below command,
s.getCell(columnID, rowID).getContents())
ex:
s.getCell(0, 1).getContents();






33. Q. How to create Excel file

A.
FileOutputStream fo=new FileOutputStream("Path to create xls file");
WritableWorkbook wb=Workbook.createWorkbook(fo);
WritableSheet ws=wb.createSheet("Results", 0);
Label un=new Label(0,0,"Username");
ws.addCell(un);
wb.write();
wb.close();


34. Q. How to print data from notepad(txt file)

A.
File f=new File("E:\\data2.txt");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
String str;
while((str=br.readLine())!=null)
{
System.out.println(str);
}



35. Q. How to create and write data into txt file

A. File f=new File("E:\\data2.txt");
FileWriter fw=new FileWriter(f);
BufferedWriter bw=new BufferedWriter(fw);
bw.write("Nagesh");
bw.newLine();
bw.write("hyderabad");
bw.newLine();
bw.write("AP");
bw.close();
fw.close();


36. Q. How to take or print data from XML file

A.
File fXmlFile = new File("D://file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Staff id : " + eElement.getAttribute("id"));
System.out.println("First Name : " +
eElement.getElementsByTagName("firstname").item(0).getTextContent());
System.out.println("Last Name : " +
eElement.getElementsByTagName("lastname").item(0).getTextContent());
System.out.println("Nick Name : " +
eElement.getElementsByTagName("nickname").item(0).getTextContent());
System.out.println("Salary : " +
eElement.getElementsByTagName("salary").item(0).getTextContent());
}
}



37. Q. What is Ant or Apache Ant

A.Ant is a Java based build management tool.
The process of converting the source code to software system (executable code) is known
as build.
There are number of steps to convert the source code to executable code. Ant will manages
all the steps with Build.xml file.

Steps to convert the Source code to software:
1. Taking the source code from src repository
2. Preparing a build area
3. Compiling the source code
4. Build the compiled code to executable code


38. Q. What is Maven

A.Maven is also Java based build management tool. It is the advanced version of Ant.



39. Q. What is the differences between Ant and Maven

A.1. Maven is widely preferred than Ant. Ant is an older tool.
2. Ant doesn't come with formal conventions such as a common project directory. Maven
consists of conventions.
3. Ant is procedural, Maven is declarative. It means in Ant, you have to specify the order
what should have to be done, where as Maven takes care of all the directories once the files
are stored in the pom.xml file.
4. Another difference that can be seen is that Ant does not have a life cycle whereas Maven
has a life cycle.
5. The scripts in Ant are not reusable where as Maven comes with reusable plugins.


40. Q. How do you handle the secured connection error in HTTPS?

A.


41. Q. How do you compare two strings or values are same.

A.


42. Q. What are the advantages and disadvantages of using Selenium as testing
tool

A.


43. Q. Write down the logic for Palindrome

A.


44. Q. How do you handle Ajax controls using selenium? i. Eg. By typing in search
engine how do you capture the auto suggestion

A.


45. Q. How do you select the 2nd item in a List box or drop down.

A.


46. Q. How do you identify an object using selenium?

A.


47. Q. Brief about your framework

A.


48. Q. What is the difference between assert and Verify Commands?

A.


49. Q. Explain about your reporting method

A.


50. Q. What is the difference between Selenium RC and Webdriver

A.


51. Q. What are all things can not be done through selenium IDE

A.


52. Q. Brief about Selenium Grid.

A.


53. Q. How to use selenium for performance testing

A.


54. Q. How to get all the links in http://google.co.in

A.


55. Q. Is it possible to handle multiple pop ups in selenium?

A.


56. Q. How is Selenium different from commercial browser automation tools?

A.


57. Q. Difference between Junit and TestNg framework

A.


58. Q. If the default port of selenium is busy then which port you use?

A.


59. Q. How much time we can save with automation

A.


60. Q. What is automation Lifecycle or Automation approach or automation plan

A.


61. Q. What is Abstraction

A.


62. Q. What is the difference between Performance, Load and Stress testing

A.


63. Q. Write a program to get all the text boxes in mail.in register page with
webdriver

A.

----------------------------------------------------------------------------------------
VERY IMPORTANT QUESTIONS ON FRAMEWORK
1. I want to skip a Test method in class, How do i do that in Junit?

Ans: place @Ignore above the @Test method.
package Employee;

import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Test;
public class Test2 {
@Ignore
@Test
public void test1()
{
System.out.println(" test in test1");
}
@Test
public void test2()
{
System.out.println(" test in test2");
}
}

Output: test in test2.

2. Suppose I have a List of classes and in that number of methods but i want to
execute Specific classes only and rest i want to skip?

Ans: If you want to Skip the classes just you need to place the @Ignore method
above the class.

Class --1
package Employee;

import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Test;

@Ignore
public class Test1 {

@Test
public void test()
{
System.out.println("Test1");
}
}

Class -- 2
package Employee;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Test;
public class Test2 {

@Test
public void test1()
{
System.out.println(" test in test1");
}
@Test
public void test2()
{
System.out.println(" test in test2");
}
}

Test Runner method.

package Employee;

import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@Suite.SuiteClasses({
Test1.class,Test2.class

})
public class Testrun {

}

Out Put: test in test2

----------------------------------------------------------------------------------------
Q: What is WebDriver?
A: WebDriver is a tool for writing automated tests of websites. It aims to mimic the behaviour of a real
user, and as such interacts with the HTML of the application.
Q: So, is it like Selenium? Or Sahi?
A: The aim is the same (to allow you to test your webapp), but the implementation is different. Rather
than running as a Javascript application within the browser (with the limitations this brings, such as the
"same origin" problem), WebDriver controls the browser itself. This means that it can take advantage of
any facilities offered by the native platform.
Q: What is Selenium 2.0?
A: WebDriver is part of Selenium. The main contribution that WebDriver makes is its API and the native
drivers.
Q: How do I migrate from using the original Selenium APIs to the new WebDriver APIs?
A: The process is described in the Selenium documentation
at http://seleniumhq.org/docs/appendix_migrating_from_rc_to_webdriver.html
Q: Which browsers does WebDriver support?
A: The existing drivers are
the ChromeDriver, InternetExplorerDriver, FirefoxDriver, OperaDriver and HtmlUnitDriver. For more
information about each of these, including their relative strengths and weaknesses, please follow the links
to the relevant pages. There is also support for mobile testing via the AndroidDriver, OperaMobileDriver
and IPhoneDriver.
Q: What does it mean to be "developer focused"?
A: We believe that within a software application's development team, the people who are best placed to
build the tools that everyone else can use are the developers. Although it should be easy to use
WebDriver directly, it should also be easy to use it as a building block for more sophisticated tools.
Because of this, WebDriver has a small API that's easy to explore by hitting the "autocomplete" button in
your favourite IDE, and aims to work consistently no matter which browser implementation you use.
Q: How do I execute Javascript directly?
A: We believe that most of the time there is a requirement to execute Javascript there is a failing in the
tool being used: it hasn't emitted the correct events, has not interacted with a page correctly, or has failed
to react when an XmlHttpRequest returns. We would rather fix WebDriver to work consistently and
correctly than rely on testers working out which Javascript method to call.
We also realise that there will be times when this is a limitation. As a result, for those browsers that
support it, you can execute Javascript by casting the WebDriver instance to a JavascriptExecutor. In
Java, this looks like:
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return document.title");
Other language bindings will follow a similar approach. Take a look at the UsingJavascript page for more
information.
Q: Why is my Javascript execution always returning null?
A: You need to return from your javascript snippet to return a value, so:
js.executeScript("document.title");
will return null, but:
js.executeScript("return document.title");
will return the title of the document.
Q: My XPath finds elements in one browser, but not in others. Why is this?
A: The short answer is that each supported browser handles XPath slightly differently, and you're
probably running into one of these differences. The long answer is on the XpathInWebDriver page.
Q: The InternetExplorerDriver does not work well on Vista. How do I get it to work as expected?
A: The InternetExplorerDriver requires that all security domains are set to the same value (either trusted
or untrusted) If you're not in a position to modify the security domains, then you can override the check
like this:
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNO
RING_SECURITY_DOMAINS, true);
WebDriver driver = new InternetExplorerDriver(capabilities);
As can be told by the name of the constant, this may introduce flakiness in your tests. If all sites are in the
same protection domain, you shouldbe okay.
Q: What about support for languages other than Java?
A: Python, Ruby, C# and Java are all supported directly by the development team. There are also
webdriver implementations for PHP and Perl. Support for a pure JS API is also planned.
Q: How do I handle pop up windows?
A: WebDriver offers the ability to cope with multiple windows. This is done by using the
"WebDriver.switchTo().window()" method to switch to a window with a known name. If the name is not
known, you can use "WebDriver.getWindowHandles()" to obtain a list of known windows. You may pass
the handle to "switchTo().window()".
Q: Does WebDriver support Javascript alerts and prompts?
A: Yes, using the Alerts API:
// Get a handle to the open alert, prompt or confirmation
Alert alert = driver.switchTo().alert();
// Get the text of the alert or prompt
alert.getText();
// And acknowledge the alert (equivalent to clicking "OK")
alert.accept();
Q: Does WebDriver support file uploads?
A: Yes.
You can't interact with the native OS file browser dialog directly, but we do some magic so that if you call
WebElement#sendKeys("/path/to/file") on a file upload element, it does the right thing. Make sure you
don't WebElement#click() the file upload element, or the browser will probably hang.
Handy hint: You can't interact with hidden elements without making them un-hidden. If your element is
hidden, it can probably be un-hidden with some code like:
((JavascriptExecutor)driver).executeScript("arguments[0].style.visibility =
'visible'; arguments[0].style.height = '1px'; arguments[0].style.width =
'1px'; arguments[0].style.opacity = 1", fileUploadElement);
Q: The "onchange" event doesn't fire after a call "sendKeys"
A: WebDriver leaves the focus in the element you called "sendKeys" on. The "onchange" event will only
fire when focus leaves that element. As such, you need to move the focus, perhaps using a "click" on
another element.
Q: Can I run multiple instances of the WebDriver sub-classes?
A: Each instance of an HtmlUnitDriver, ChromeDriver and FirefoxDriver is completely independent of
every other instance (in the case of firefox and chrome, each instance has its own anonymous profile it
uses). Because of the way that Windows works, there should only ever be a
singleInternetExplorerDriver instance at one time. If you need to run more than one instance of
the InternetExplorerDriver at a time, consider using the Remote!WebDriver and virtual machines.
Q: I need to use a proxy. How do I configure that?
A: Proxy configuration is done via the org.openqa.selenium.Proxy class like so:
Proxy proxy = new Proxy();
proxy.setProxyAutoconfigUrl("http://youdomain/config");

// We use firefox as an example here.
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(CapabilityType.PROXY, proxy);

// You could use any webdriver implementation here
WebDriver driver = new FirefoxDriver(capabilities);
Q: How do I handle authentication with the HtmlUnitDriver?
A: When creating your instance of the HtmlUnitDriver, override the "modifyWebClient" method, for
example:
WebDriver driver = new HtmlUnitDriver() {
protected WebClient modifyWebClient(WebClient client) {
// This class ships with HtmlUnit itself
DefaultCredentialsProvider creds = new DefaultCredentialsProvider();

// Set some example credentials
creds.addCredentials("username", "password");

// And now add the provider to the webClient instance
client.setCredentialsProvider(creds);

return client;
}
};
Q: Is WebDriver thread-safe?
A: WebDriver is not thread-safe. Having said that, if you can serialise access to the underlying driver
instance, you can share a reference in more than one thread. This is not advisable. You /can/ on the
other hand instantiate one WebDriver instance for each thread.
Q: How do I type into a contentEditable iframe?
A: Assuming that the iframe is named "foo":
driver.switchTo().frame("foo");
WebElement editable = driver.switchTo().activeElement();
editable.sendKeys("Your text here");
Sometimes this doesn't work, and this is because the iframe doesn't have any content. On Firefox you
can execute the following before "sendKeys":
((JavascriptExecutor) driver).executeScript("document.body.innerHTML =
'<br>'");
This is needed because the iframe has no content by default: there's nothing to send keyboard input to.
This method call inserts an empty tag, which sets everything up nicely.
Remember to switch out of the frame once you're done (as all further interactions will be with this specific
frame):
driver.switchTo().defaultContent();
Q: WebDriver fails to start Firefox on Linux due to java.net.SocketException
A: If, when running WebDriver on Linux, Firefox fails to start and the error looks like:
Caused by: java.net.SocketException: Invalid argument
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:365)
at java.net.Socket.bind(Socket.java:571)
at
org.openqa.selenium.firefox.internal.SocketLock.isLockFree(SocketLock.java:99
)
at
org.openqa.selenium.firefox.internal.SocketLock.lock(SocketLock.java:63)
It may be caused due to IPv6 settings on the machine. Execute:
sudo sysctl net.ipv6.bindv6only=0
To get the socket to bind both to IPv6 and IPv4 addresses of the host with the same calls. More
permanent solution is disabling this behaviour by editing /etc/sysctl.d/bindv6only.conf
Q: WebDriver fails to find elements / Does not block on page loads
A: This problem can manifest itself in various ways:
Using WebDriver.findElement(...) throws ElementNotFoundException, but the element is clearly
there - inspecting the DOM (using Firebug, etc) clearly shows it.
Calling Driver.get returns once the HTML has been loaded - but Javascript code triggered by the
onload event was not done, so the page is incomplete and some elements cannot be found.
Clicking on an element / link triggers an operation that creates new element. However, calling
findElement(s) after click returns does not find it. Isn't click supposed to be blocking?
How do I know when a page has finished loading?
Explanation: WebDriver has a blocking API, generally. However, under some conditions it is possible for
a get call to return before the page has finished loading. The classic example is Javascript starting to run
after the page has loaded (triggered by onload). Browsers (e.g. Firefox) will notify WebDriver when the
basic HTML content has been loaded, which is when WebDriver returns. It's difficult (if not impossible) to
know when Javascript has finished executing, since JS code may schedule functions to be called in the
future, depend on server response, etc. This is also true for clicking - when the platform supports native
events (Windows, Linux) clicking is done by sending a mouse click event with the element's coordinates
at the OS level - WebDriver cannot track the exact sequence of operations this click creates. For this
reason, the blocking API is imperfect - WebDriver cannot wait for all conditions to be met before the test
proceeds because it does not know them. Usually, the important matter is whether the element involved
in the next interaction is present and ready.
Solution: Use the Wait class to wait for a specific element to appear. This class simply calls findElement
over and over, discarding the NoSuchElementException each time, until the element is found (or a
timeout has expired). Since this is the behaviour desired by default for many users, a mechanism for
implicitly-waiting for elements to appear has been implemented. This is accessible through
theWebDriver.manage().timeouts() call. (This was previously tracked on issue 26).
Q: How can I trigger arbitrary events on the page?
A: WebDriver aims to emulate user interaction - so the API reflects the ways a user can interact with
various elements.
Triggering a specific event cannot be achieved directly using the API, but one can use the Javascript
execution abilities to call methods on an element.
Q: Why is it not possible to interact with hidden elements?
A: Since a user cannot read text in a hidden element, WebDriver will not allow access to it as well.
However, it is possible to use Javascript execution abilities to call getText directly from the element:
WebElement element = ...;
((JavascriptExecutor) driver).executeScript("return
arguments[0].getText();", element);
Q: How do I start Firefox with an extension installed?
A:
FirefoxProfile profile = new FirefoxProfile()
profile.addExtension(....);

WebDriver driver = new FirefoxDriver(profile);
Q: I'd like it if WebDriver did....
A: If there's something that you'd like WebDriver to do, or you've found a bug, then please add an add an
issue to the WebDriver project page.
Q: Selenium server sometimes takes a long time to start a new session ?
A: If you're running on linux, you will need to increase the amount of entropy available for secure random
number generation. Most linux distros can install a package called "randomsound" to do this.
On Windows (XP), you may be running into http://bugs.sun.com/view_bug.do?bug_id=6705872, which
usually means clearing out a lot of files from your temp directory. temp directory.
Q: What's the Selenium WebDriver API equivalent to TextPresent ?
A:
driver.findElement(By.tagName("body")).getText()
will get you the text of the page. To verifyTextPresent/assertTextPresent, from that you can use your
favourite test framework to assert on the text. To waitForTextPresent, you may want to investigate
the WebDriverWait class.
Q: The socket lock seems like a bad design. I can make it better
A: the socket lock that guards the starting of firefox is constructed with the following design constraints:
It is shared among all the language bindings; ruby, java and any of the other bindings can coexist
at the same time on the same machine.
Certain critical parts of starting firefox must be exclusive-locked on the machine in question.
The socket lock itself is not the primary bottleneck, starting firefox is.
The SocketLock is an implementation of the Lock interface. This allows for a pluggable strategy for your
own implementation of it. To switch to a different implementation, subclass the FirefoxDriver and override
the "obtainLock" method.
Q: Why do I get a UnicodeEncodeError when I send_keys in python
A: You likely don't have a Locale set on your system. Please set a locale LANG=en_US.UTF-8 and
LC_CTYPE="en_US.UTF-8" for example.

----------------------------------------------------------------------------------------
JAVA AND JUNIT INTERVIEW QUESTIONS AND ANSWERS
MOST FREQUENTLY ASKED JUNIT INTERVIEW QUESTIONS
How To Wirte a Simple JUnit Test Class?
import org.junit.*;

public class HelloTest {
@Test
public void testHello() {
String message = "Hello World!";
Assert.assertEquals(12, message.length());
}
}

What is JUnit?
It is a software testing framework to for unit testing.
It is written in Java and designed to test Java applications.
It is an Open Source Software maintained by the JUnit.org community.

Answer from the JUnit FAQ:

JUnit is a simple, open source framework to write and run repeatable tests. It is an instance of
the xUnit architecture for unit testing frameworks. JUnit features include:

Assertions for testing expected results
Test fixtures for sharing common test data
Test runners for running tests

JUnit was originally written by Erich Gamma and Kent Beck.

Why Do You Use JUnit to Test Your Code?
I believe that writing more tests will make me more productive, not less productive.
I believe that tests should be done as soon as possible at the code unit level.
I believe that using JUnit makes unit testing easier and faster.

Who Should Use JUnit, Developers or Testers?
JUnit is mostly used by developers. JUnit is designed for unit testing, which is really a coding
process, not a testing process.

But many testers or QA engineers, are also required to use JUnit for unit testing. For example, I
found this job title on the Internet: Lead QA Engineer - Java / J2EE / whitebox / SAP / Junit

When Should Unit Tests Should Be Written In Development Cycle?
If you are a TDD (Test-Driven Development) believer, you should write unit test before writing
the code. Test-first programming is practiced by only writing new code when an automated test
is failing.

Good tests tell you how to best design the system for its intended use. They effectively
communicate in an executable format how to use the software. They also prevent tendencies to
over-build the system based on speculation. When all the tests pass, you know you're done!

Whenever a customer test fails or a bug is reported, first write the necessary unit test(s) to
expose the bug(s), then fix them. This makes it almost impossible for that particular bug to
resurface later.

Test-driven development is a lot more fun than writing tests after the code seems to be working.
Give it a try!

How Do You Test a Method That Does not Return Anything?

You need to follow the logic below to answer this question:

* If a method is not returning anything through the "return" statement (void method), it may
return data through its arguments. In this case, you can test the data returned in any argument.
* Else if a method is not returning any data through its arguments, it may change values of its
instance variables. In this case, you can test changes of any instance variables.
* Else if a method is not changing any instance variable, it may change values of its class
variables. In this case, you can test changes of any class variables.
* Else if a method is not changing any class variable, it may change external resources. In this
case, you can test changes of any external resources.
* Else if a method is not changing any external resources, it may just doing nothing but holding
the thread in a waiting status. In this case, you can test this waiting condition.
* Else if a method is not holding the thread in waiting status, then this method is really doing
nothing. In this case, there is no need to test this method. :-)

When Objects Are Garbage Collected After a Test Is Executed?
My guess would be that all objects used in a test will be ready for Java garbage collector to
release them immediately after the test has been executed.

By design, the tree of Test instances is built in one pass, then the tests are executed in a second
pass. The test runner holds strong references to all Test instances for the duration of the test
execution. This means that for a very long test run with many Test instances, none of the tests
may be garbage collected until the end of the entire test run.

Therefore, if you allocate external or limited resources in a test, you are responsible for freeing
those resources. Explicitly setting an object to null in the tearDown() method, for example,
allows it to be garbage collected before the end of the entire test run.

If this is true, the JUnit runner should be improved to stop building all test instances before
executing any tests. Instead, the JUnit runner should just take one test at a time, build an instance
of this test, execute the test, and release the test when the execution is done.

Do You Have To Write a Test for Everything?
No, just test everything that could reasonably break.

Be practical and maximize your testing investment. Remember that investments in testing are
equal investments in design. If defects aren't being reported and your design responds well to
change, then you're probably testing enough. If you're spending a lot of time fixing defects and
your design is difficult to grow, you should write more tests.

If something is difficult to test, it's usually an opportunity for a design improvement. Look to
improve the design so that it's easier to test, and by doing so a better design will usually emerge.


Dear readers, these JUnit Interview Questions have been designed specially to
get you acquainted with the nature of questions you may encounter during your
interview for the subject of JUnit. As per my experience good interviewers hardly
plan to ask any particular question during your interview, normally questions start
with some basic concept of the subject and later they continue based on further
discussion and what you answer:
Q: What is testing?
A: Testing is the process of checking the functionality of the application whether it
is working as per requirements.
Q: What is unit testing?
A: Unit testing is the testing of single entity (class or method). Unit testing is very
essential to every software company to give a quality product to their customers.
Q: What is Manual testing?
A: Executing the test cases manually without any tool support is known as manual
testing.
Q: What is Automated testing?
A: Taking tool support and executing the test cases by using automation tool is
known as automation testing.
Q: Out of Manual and Automated testing which one is better and why?
A: Manual Testing is:
1. Time consuming and tedious.
2. Huge investment in human resources.
3. Less reliable.
4. Non-programmable.
Automated testing is
1. Fast
2. Less investment in human resources
3. More reliable
4. Programmable
Q: What is JUnit?
A: JUnit is a unit testing framework for the Java Programming Language. It is
written in Java and is an Open Source Software maintained by the JUnit.org
community.
Q: What are important features of JUnit?
A: Import features of JUnit are:
1. It is an open source framework.
2. Provides Annotation to identify the test methods.
3. Provides Assertions for testing expected results.
4. Provides Test runners for running tests.
5. JUnit tests can be run automatically and they check their own results and provide
immediate feedback.
6. JUnit tests can be organized into test suites containing test cases and even other
test suites.
7. JUnit shows test progress in a bar that is green if test is going fine and it turns red
when a test fails.
Q: What is a Unit Test Case?
A: A Unit Test Case is a part of code which ensures that the another part of code
(method) works as expected. A formal written unit test case is characterized by a
known input and by an expected output, which is worked out before the test is
executed. The known input should test a precondition and the expected output
should test a post condition.
Q: When are Unit Tests written in Development Cycle?
A: Tests are written before the code during development in order to help coders
write the best code.
Q: Why not just use System.out.println() for testing?
A: Debugging the code using system.out.println() will lead to manual scanning of
the whole output every time the program is run to ensure the code is doing the
expected operations. Moreover, in the long run, it takes lesser time to code JUnit
methods and test them on class files.
Q: How to install JUnit?
A: Follow the steps below:
1. Download the latest version of JUnit, referred to below as junit.zip.
2. Unzip the junit.zip distribution file to a directory referred to as %JUNIT_HOME%.
3. Add JUnit to the classpath:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar
4. Test the installation by running the sample tests distributed with JUnit (sample
tests are located in the installation directory directly, not the junit.jar file). Then
simply type:
java org.junit.runner.JUnitCore org.junit.tests.AllTests
All the tests should pass with an "OK" message. If the tests don't pass, verify that
junit.jar is in the CLASSPATH.
Q: Why does JUnit only report the first failure in a single test?
A: Reporting multiple failures in a single test is generally a sign that the test does
too much and it is too big a unit test. JUnit is designed to work best with a number
of small tests. It executes each test within a separate instance of the test class. It
reports failure on each test.
Q: In Java, assert is a keyword. Won't this conflict with JUnit's assert()
method?
A: JUnit 3.7 deprecated assert() and replaced it with assertTrue(), which works
exactly the same way. JUnit 4 is compatible with the assert keyword. If you run
with the -ea JVM switch, assertions that fail will be reported by JUnit.
Q: How do I test things that must be run in a J2EE container (e.g.
servlets, EJBs)?
A: Refactoring J2EE components to delegate functionality to other objects that don't
have to be run in a J2EE container will improve the design and testability of the
software. Cactusis an open source JUnit extension that can be used for unit testing
server-side java code.
Q: What are JUnit classes? List some of them.
A: JUnit classes are important classes which are used in writing and testing JUnits.
Some of the important classes are:
1. Assert - A set of assert methods.
2. TestCase - It defines the fixture to run multiple tests.
3. TestResult - It collects the results of executing a test case.
4. TestSuite - It is a Composite of Tests.
Q: What are annotations and how are they useful in JUnit?
A: Annotations are like meta-tags that you can add to you code and apply them to
methods or in class.
The annotation in JUnit gives us information about test methods, which methods
are going to run before & after test methods, which methods run before & after all
the methods, which methods or class will be ignore during execution.
Q: How will you run JUnit from command window?
A: Follow the steps below:
1. Set the CLASSPATH
2. Invoke the runner:
3. java org.junit.runner.JUnitCore.

Q: What is JUnitCore class?
A: JUnitCore is an inbuilt class in JUnit package. It is based on Facade design
pattern. This class is used to run only specified test classes.
Q: What is Test suite?
A: Test suite means bundle a few unit test cases and run it together. In JUnit, both
@RunWith and @Suite annotation are used to run the suite test.
Q: What is @Ignore annotation and how is this useful?
A: Sometimes it happens that our code is not ready and test case written to test
that method/code will fail if run. The @Ignore annotation helps in this regards.
Following are some of the usefulness of @Ignore annotation:
1. You can easily identify all @Ignore annotations in the source code, while
unannotated or commented out tests are not so simple to find.
2. There are cases when you can't fix a code that is failing, but you still want to
method to be around, precisely so that it does not get forgotten. In such cases
@Ignore makes sense.
Q: What are Parameterized tests?
A: Parameterized tests allow developer to run the same test over and over again
using different values.
Q: How do you use test fixtures?
A: Fixtures is a fixed state of a set of objects used as a baseline for running tests.
The purpose of a test fixture is to ensure that there is a well known and fixed
environment in which tests are run so that results are repeatable. It includes:
1. setUp() method which runs before every test invocation.
2. tearDown() method which runs after every test method.
Q: How to compile a JUnit Test Class?
A: Compiling a JUnit test class is like compiling any other Java classes. The only
thing you need watch out is that the JUnit JAR file must be included in the
classpath.
Q: What happens if a JUnit Test Method is Declared as "private"?
A: If a JUnit test method is declared as "private", it compiles successfully. But the
execution will fail. This is because JUnit requires that all test methods must be
declared as "public".
Q: How do you test a "protected" method?
A: When a method is declared as "protected", it can only be accessed within the
same package where the class is defined. Hence to test a "protected" method of a
target class, define your test class in the same package as the target class.
Q: How do you test a "private" method?
A: When a method is declared as "private", it can only be accessed within the same
class. So there is no way to test a "private" method of a target class from any test
class. Hence you need to perform unit testing manually. Or you have to change
your method from "private" to "protected".
Q: What happens if a JUnit test method is declared to return "String"?
A: If a JUnit test method is declared to return "String", the compilation will pass ok.
But the execution will fail. This is because JUnit requires that all test methods must
be declared to return "void".
Q: How can you use JUnit to test that the code throws desired
exception?
A: JUnit provides a option of tracing the Exception handling of code. You can test if
a code throws desired exception or not. The expected parameter is used along with
@Test annotation as follows: @Test(expected)
Q: What are Parameterized tests in JUnit?
A: Parameterized tests allow developer to run the same test over and over again
using different values.
Q: How to create Parameterized tests?
A: There are five steps, which you need to follow to create Parameterized tests:
1. Annotate test class with @RunWith(Parameterized.class).
2. Create a public static method annotated with @Parameters that returns a
Collection of Objects (as Array) as test data set.
3. Create a public constructor that takes in what is equivalent to one "row" of test
data.
4. Create an instance variable for each "column" of test data.
5. Create your tests case(s) using the instance variables as the source of the test
data.
The test case will be invoked once per each row of data.
Q: Can you use a main() Method for Unit Testing?
A: Yes you can test using main() method. One obvious advantage seems to be that
you can whitebox test the class. That is, you can test the internals of it (private
methods for example). You can't do that with unit-tests. But primarily the test
framework tests the interface and the behavior from the user's perspective.
Q: Do you need to write a test class for every class that needs to be
tested?
A: No. We need not write an independent test class for every class that needs to be
tested. If there is a small group of tests sharing a common test fixture, you may
move those tests to a new test class.
Q: When are tests garbage collected?
A: The test runner holds strong references to all Test instances for the duration of
the test execution. This means that for a very long test run with many Test
instances, none of the tests may be garbage collected until the end of the entire
test run. Explicitly setting an object to null in the tearDown() method, for example,
allows it to be garbage collected before the end of the entire test run.
WHAT IS NEXT ?
Further you can go through your past assignments you have done with the subject
and make sure you are able to speak confidently on them. If you are fresher then
interviewer does not expect you will answer very complex questions, rather you
have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it
matters that whatever you answered, you must have answered with confidence. So
just feel confident during your interview. We at tutorialspoint wish you best luck to
have a good interviewer and all the very best for your future endeavor. Cheers :-)

Q: How can we test a method that do not return anything?
A method may change value of instance variables, if it does not return anything. In this case
we can check value of instance variables.
A method may not return any thing but it may modify the objects that are referenced by the
object references which are passed in arguments. In this case we can test the state of these referenced
objects.
If method does not change any of above, It may change value of static members. In this case
we may check change in value of static variables.
Otherwise if a method is not changing any variable, it may be changing external resources. In
this case, you can test changes of any external resources. These external resources may be a file.
Otherwise if a method is not changing any external resources, it may just doing nothing but
holding the thread in a waiting status. In this case, you can test this waiting condition.
Most of the times a method may be doing one or more of above things which can be tested. more

Q: Can we declare JUnit test methods private?
Junit test methods cannot be declared as private. If we do so, the test case will compile successfully
however execution of the test will fail. This is because JUnit requires that all the test methods must
be declared as public.

Q: What is a test suite?
A TestSuite is group of tests. It runs a collection of test cases. This is a convenient way to group
related test cases. ex.

void testSu() {
TestSuite testSuite=new TestSuite("Some test suite");
testSuite.add(test1.class);
testSuite.add(test2.class);
}

Q: When are test garbage collected ?
The Test instances tree is built in one pass and then the tests are executed in a second pass. The test
runner holds references to all Test instances for the duration of the test execution. This means that for
a long test run with many Test instances, none of the tests may be garbage collected until the end of
the entire test run.
Therefore, if you allocate external or limited resources in a test, tester is responsible for freeing those
resources. Explicitly setting an object to null in the tearDown() method, allows it to be garbage
collected before the end of the entire test run and is also recommended.

Q: Can we pass command-line arguments to a test execution?
Yes, we can do so by using
-D JVM command-line options
like: -DnameOfParameter=parameterValue

Q: What Happens If we Run JUnit Tests with Java Assertion Enabled?
As of JUnit 3.8, The JUnit runner works well with Java assertions. If Java assertion is enabled and a
Java assert statement fails, the JUnit runner will flag this in same way as the calling test fails.

JUnit (Java Unit Testing) interview questions and answers
by Chaitanya Singh
in Java Q&A
Hello Guys, The below Junit interview questions and answers are for both freshers as well as for
experienced folks. The reason behind this is that generally interviewers start with the basic questions
(fresher level) and go for questions related to advanced topics ( experienced level) later. The whole
FAQs are divided in two sections. This is the first part.
Must read Q&A second part here: JUnit interview questions
Question: What is unit testing?
Answer: A complete application can be build up by integrating small-2 functional parts, such parts
are called as units. It is always better to test such individual units before testing the entire
application. The process of testing the functionality and working of these individual unit is known as
unit testing. Unit testing can be done manually and the process can also be automated.
Question: Explain Manual testing vs Automated testing?
Answer: Manual testing: Test cases are executed by humans, its time consuming and
costly. Automated Testing: No human involvement, test cases are executed by automated tools and
programs, Its fast and less costly compared to manual testing.
Question: What is a Unit Test Case?
Answer: Unit test case is nothing but a combination of input data and expected output, which is
defined to test the proper functionality of a individual test unit. Its is just to test the behavior of the
unit for a particular input data.
Question: Why does JUnit only report the first failure in a single test?
Answer: There is no particular answer for this question, the main reason it does it like this to make
the testing process simple and easy. Even though the failures are more than one it only reports the
first failure, resolving which may implicitly resolve other unreported failures too.
Question: What is @Test and where its used?
@Test annotation is used to mark a method as test method, result of which is then compared with
expected output to check whether the test is successful or not.
Question: What is @Before and @BeforeClass and its usage?
@Before annotation:
syntax:
@Before
public void myMethod()
This method should execute before each test. Such methods are generally used for initialization
before performing a actual test in test environment.
@BeforeClass annotation:
syntax:
@BeforeClass
public static void myMethod()
This method should execute before all the tests. It executes only once. Method should be declared
static. Mostly used for database connectivity tasks before execution of any of the test.
Question: What is @After and @AfterClass and its usage?
@After annotation:
syntax:
@After
public void myMethod()
This method should execute after each test and used for cleaning up the test and temporary data to
avoid memory issues.
@AfterClass annotation:
syntax:
@AfterClass
public static void myMethod()
This method should execute at the end, once all the tests are finished. Method should be declared
static and executes only a single time. Mostly used for closing the database connection.
Question: What is @Ignore and when its used?
@Ignore is used to ignore a test method. Its really useful when we have all the tests in advance but
the code is yet to be tested for the particular test, in such scenarios such test methods should be
marked with @Ignore annotation.
Question: How will you run JUnit from command window?
Answer:
1) First set the ClassPath as follows:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%junit.jar
2) Invoke JunitCore
java org.junit.runner.JUnitCore
Question: What is JUnitCore class?
Answer: This class is mainly responsible for executing tests. The org.junit.runner.JUnitCore class
has a runClasses() method, which allows us to run one or more test classes. As a output we get a
Result (org.junit.runner.Result) object, which we use to filter out the test information.
Question: What is Parameterized test in JUnit and what all annotations used for this?
Answer: Parameterized tests are possible in JUnit and they provides us the liberty of passing
parameters into the test classes.
@RunWith(Parameterized.class) For making a class parametrized.
@Parameters - Parameterized class must have a static method for generating and returning a
collection of array, this method should be marked with @Parameters annotation.
Question: Whats the use of @Rule annotation?
Answer: @Rule annotation is used for creating objects, which later can be used in test methods.
Question: When you should run JUnit test, Is there any particular time interval between each
run?
Answer: No there is no time constraint. A JUnit test needs to run whenever there is a change in the
source code. This ensures that the new change passes through all the tests.
Question: Can we change return type of JUnit test method from void to some other type?
Answer: Ideally you should not do this. All the JUnit test methods should have a void return type. If
you change the return type then the test method would not be considered as a test method and would
be ignored during execution of tests.
Question: Is it possible to pass command-line arguments to a test execution?
Answer: Yes, Its possible to pass command line arguments to a test execution -
You should use this command:
-D JVM command-line options
Question: How @Test annotation is used for testing exceptions?
Answer: @Test (expected = Exception.class)
Limitation: It is used for testing only a single exception.
This is Part 2 of Q&A. Read first part here - JUnit (Java Unit Testing) interview questions and
answers Part1.
Question1: What is Junit?
Answer: Java + unit testing = Junit
1. Junit is open source testing framework developed for unit testing java code and is
now the default framework for testing Java development.
2. It has been developed by Erich Gamma and Kent Beck.
3. It is an application programming interface for developing test cases in java which is
part of the XUnit Family.
4. It helps the developer to write and execute repeatable automated tests.
5. Eclipse IDE comes with both Junit and its plug-in for working with Junit.
6. Junit also has been ported to various other languages like PHP, Python, C++ etc.
Question2: Who should use Junit, developers or testers?
Answer: Used by developers to implement unit tests in Java. Junit is designed for unit testing, which
is really a coding process, not a testing process. But many testers or QA engineers are also required
to use Junit for unit testing.
Question3: Why do you use Junit to test your code?
Answer: Junit provides a framework to achieve all the following-:
1. Test early and often automated testing.
2. Junit tests can be integrated with the build so regression testing can be done at unit
level.
3. Test Code reusage.
4. Also when there is a transfer Junit tests act as a document for the unit tests.
Question4: How do you install Junit?
Answer: Lets see the installation of Junit on windows platform:
1. Download the latest version of Junit from http://download.sourceforge.net/junit/
2. Uncompress the zip to a directory of your choice.
3. Add JUnit to the classpath:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%junit.jar
4. Test the installation by running the sample tests that come along with Junit located in the
installation directory. Therefore, make sure that the JUnit installation directory is on your
CLASSPATH. Then simply type:
java org.junit.runner.JUnitCore org.junit.tests.AllTests
All the tests should pass with an OK message. If the tests dont pass, verify that junit.jar is in the
CLASSPATH.
Question5: What are unit tests?
Answer: A unit test is nothing more than the code wrapper around the application code that can be
executed to view pass fail results.
Question6: When are Unit Tests written in Development Cycle?
Answer: Tests are written before the code during development in order to help coders write the best
code. Test-driven development is the ideal way to create a bug free code. When all tests pass, you
know you are done! Whenever a test fails or a bug is reported, we must first write the necessary unit
test(s) to expose the bug(s), and then fix them. This makes it almost impossible for that particular bug
to resurface later.
Question7: How to write a simple Junit test class?
Answer: To write a test case, follow these steps:
1. Define a subclass of TestCase.
2. Override the setUp() method to initialize object(s) under test.
3. Optionally override the tearDown() method to release object(s) under test.
Define one or more public testXYZ() methods that exercise the object(s) under test and assert
expected results.
Question8: What Is Junit TestCase?
Answer: JUnit TestCase is the base class, junit.framework.TestCase, that allows you to create a test
case. (Although, TestCase class is no longer supported in JUnit 4.4.)
A test case defines the fixture to run multiple tests. To define a test case
-Implement a subclass of TestCase
-Define instance variables that store the state of the fixture
-Initialize the fixture state by overriding setUp
-Clean-up after a test by overriding tearDown
Each test runs in its own fixture so there can be no side effects among test runs.
Question9: What Is Junit TestSuite?
Answer: JUnit TestSuite is a container class under package junit.framework.TestSuite. It allows us
to group multiple test cases into a collection and run them together. (JUnit 4.4 does not support
TestSuite class now).
Question10: What is Junit Test Fixture?
Answer: A test fixture is a fixed state of a set of objects used as a baseline for running tests. Their
purpose is to ensure that there is a well known and fixed environment in which tests are run so that
results are repeatable. Examples of fixtures:
Loading a database with a specific, known set of data
Copying a specific known set of files
Preparation of input data and setup/creation of fake or mock objects
If a group of tests shares the same fixtures, you should write a separate setup code to create the
common test fixture. If a group of tests requires different test fixtures, you can write code inside the
test method to create its own test fixture.
Question11: What happens if a Junit test method is declared as private?
Answer: If a Junit test method is declared as private, the compilation will pass ok. But the
execution will fail. This is because Junit requires that all test methods must be declared as public.
Question12: What happens If a Junit test method Is declared to return String?
Answer: If a Junit test method is declared to return String, the compilation will pass ok. But the
execution will fail. This is because Junit requires that all test methods must be declared to return
void.
Question13: Why not just use system.out.println () for Unit Testing?
Answer: Debugging the code using system.out.println() will lead to manual scanning of the whole
output every time the program is run to ensure the code is doing the expected operations. Moreover,
in the long run, it takes lesser time to code Junit methods and test them on our files.
Question14: The methods Get () and Set () should be tested for which conditions?
Answer: Unit tests performed on java code should be designed to target areas that might break. Since
the set() and get() methods on simple data types are unlikely to break, there is no need to test them
explicitly. On the other hand, set() and get() methods on complex data types are vulnerable to break.
So they should be tested.
Question15: For which conditions, the methods Get () and Set () can be left out for testing?
Answer: You should do this test to check if a property has already been set (in the constructor) at the
point you wish to call getX(). In this case you must test the constructor, and not the getX() method.
This kind of test is especially useful if you have multiple constructors.
Question16: Do you need to write a test class for every class that needs to be tested?
Answer: No. We need not write an independent test class for every class that needs to be tested. If
there is a small group of tests sharing a common test fixture, you may move those tests to a new test
class. If you have two groups of tests that you think youd like to execute separately from one
another, it is wise to place them in separate test classes.
Question17: How do you test a protected method?
Answer: A protected method can only be accessed within the same package where the class is
defined. So, testing a protected method of a target class means we need to define your test class in the
same package as the target class.
Question18: How do you test a private method?
Answer: A private method only be accessed within the same class. So there is no way to test a
private method of a target class from any test class. A way out is that you can perform unit testing
manually or can change your method from private to protected.
Question19: Do you need to write a main () method compulsorily in a Junit test case class?
Answer: No. But still developers write the main() method in a JUnit test case class to call a JUnit
test runner to run all tests defined in this class like:
public static void main(String[] args) {
junit.textui.TestRunner.run(Calculator.class);
}
Since you can call a JUnit runner to run a test case class as a system command, explicit main() for a
Junit test case is not recommended. junit.textui.TestRunner.run() method takes the test class name as
its argument. This method automatically finds all class methods whose name starts with test. Thus it
will result in below mentioned findings:
1. testCreateLogFile()
2. testExists()
3. testGetChildList()
It will execute each of the 3 methods in unpredictable sequence (hence test case methods should be
independent of each other) and give the result in console.
Question20: What happens if a test method throws an exception?
Answer: If you write a test method that throws an exception by itself or by the method being tested,
the JUnit runner will declare that test as fail.
The example test below is designed to let the test fail by throwing the uncaught
IndexOutOfBoundsException exception:
import org.junit.*;
import java.util.*;
public class UnexpectedExceptionTest2 {
// throw any unexpected exception
@Test public void testGet() throws Exception {
ArrayList emptyList = new ArrayList();
Exception anyException = null; // don't catch any exception
Object o = emptyList.get(1); }
}
If you run this test, it will fail:
OUTPUT:
There was 1 failure:
testGet(UnexpectedExceptionTest2)
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at UnexpectedExceptionTest2.testGet(UnexpectedExceptionTest2.ja
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAcce
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMe
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java
at org.junit.internal.runners.MethodRoadie.runTestMethod(Method
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.j
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestTh
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.jav
at org.junit.internal.runners.JUnit4ClassRunner.invokeTestMetho
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUni
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4Cla
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassR
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoa
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4Class
at org.junit.internal.runners.CompositeRunner.runChildren(Compo
at org.junit.internal.runners.CompositeRunner.run(CompositeRunn
at org.junit.runner.JUnitCore.run(JUnitCore.java:130)
at org.junit.runner.JUnitCore.run(JUnitCore.java:109)
at org.junit.runner.JUnitCore.run(JUnitCore.java:100)
at org.junit.runner.JUnitCore.runMain(JUnitCore.java:81)
at org.junit.runner.JUnitCore.main(JUnitCore.java:44)
FAILURES!!!
Tests run: 1, Failures: 1
Question21: When objects are garbage collected after a test is executed?
Answer: By design, the tree of Test instances is built in one pass. Then the tests are executed in a
second pass. The test runner holds strong references to all Test instances for the duration of the test
execution. This means that for a very long test run with many Test instances, none of the tests may be
garbage collected until the end of the entire test run. Therefore, if you allocate external or limited
resources in a test, you are responsible for freeing those resources. Explicitly setting an object to null
in the tearDown() method, for example, allows it to be garbage collected before the end of the entire
test run.
Question22: What is Java assert statement?
Answer: Java assertions allow the developer to put assert statements in Java source code to help
unit testing and debugging.
An assert statement has the following format:
assert boolean_expression : string_expression;
When this statement is executed:
If boolean_expression evaluates to true, the statement will pass normally.
If boolean_expression evaluates to false, the statement will fail with an AssertionError
exception.
Helper methods which help to determine if the methods being tested are performing correctly or not
assertEquals([String message], expected, actual) any kind of object can be used for
testing equality native types and objects, also specify tolerance when checking for equality in case
of floating point numbers.
assertNull([String message], java.lang.Objectobject) asserts that a given object is null
assertNotNull([String message], java.lang.Objectobject) asserts that a given object
isnotnull
assertTrue([String message], Boolean condition) Asserts that the given Boolean condition
is true
assertFalse([String message], Boolean condition) Asserts that the given Boolean
condition is false
fail([String message]) Fails the test immediately with the optional message
Example-:
public void testSum() {
int num1 = 15;
int num2 = 50;
int total = 35;
int sum = 0;
sum = num1 + num2;
assertEquals(sum, total);
}
100+ Core Java Interview Questions
by Chaitanya Singh
in Java Q&A
JAVA OOPS INTERVIEW QUESTIONS
Q) Three Principles of OOPS language?
Inheritance
Polymorphism
Data Encapsulation
Q) Java vs. C ++?
Simple
Multi-threaded
Distributed Application
Robust
Security
Complexities are removed (Pointers, Operator overloading, Multiple inheritance).
Q) What is javac ?
It produces the java byte code when *.java is given as input and it is the
intermediate representation of your source code that contains instructions that the
java interpreter will execute.
Q) What all terms are related to OOPs?
Class
Object
Methods
Inheritance
Polymorphism
Overriding
Abstraction
Encapsulation
Interface
Q) What is class?
Class is nothing but a template, which describes the various properties and
functions.
Q) What is an object?
Object has its own properties and functionality; also its an instance of the class.
Q) How many times does the garbage collector calls the finalize() method
for an object?
The garbage collector calls the finalize() method Only once for an object.
Q) What are two different ways to call garbage collector?
System.gc() OR Runtime.getRuntime().gc().
Q) Can the Garbage Collection be forced by any means?
No, its not possible. you cannot force garbage collection. you can call system.gc()
methods for garbage collection but it does not guarantee that garbage collection
would be done.
Q) Abstract class?
A class for which object cant be instantiated/created, such class are called
as Abstract class. Also a class, which is, generalized form that will be shared by all
of its subclasses, leaving it to each subclass to fill in the details.
Q) Multiple Inheritances?
Inheriting more than one parent class. Java doesnt supports multiple inheritances
whereas c++ supports.
Q) What is the method overriding?
In inheritance, when a child class writes a method with the same name as method
in super-class is called method overriding. Method call on the child class will
execute the child class method not the super class method.
There can be no object of an abstract class.
Constructors or static methods cannot be declared as abstract.
Q) Can this keyword be assigned null value?
No, this keyword cannot have null values assigned to it.
Q) What is a WeakHashMap?
a) A hash table map with duplictate keys.
b) A general purpose hash table-based implementation to better store.
c) A hash table-based Map implementation with weak keys.
d) A list with weak references to objects.
Ans is option (c).
WeakHashMap is a hash table-based Map implementation with weak keys.
Q) Which of the following lines allow main method to be executed by
ClassLoader?
a) public static String main(String a[]);
b) protected static void main(String a[]);
c) final public static void main(String a[]);
d) public static void main();
e) private static void main(String a[]);
f) public void main(String a[]);
Ans is (c). In order for the ClassLoader to execute the main() method, it has to be
declared atleast as public, static & void.
Q) Which modifiers a method of local inner class can have?
Only abstract or final keyword is allowed.
Q) Do we need to implement any method of Serializable interface to make
an object serializable?
No.In order to make an object serializable we just need to implement the interface
Serializable. We dont need to implement any methods.
Q) What is a transient variable?
transient variables are not included in the process of serialization.
They are not the part of the objects serialized state.
Variables which we dont want to include in serialization are declared as transient.
Q) Does a static nested class have access to the enclosing class non-static
methods or instance variables?
No. A static nested class doesnt have access to the enclosing class non-static
methods or instance variables.
Q) Which modifiers can be applied to the inner class?
public ,private , abstract, final, protected.
Q) Polymorphism?
In a class, 2 methods with same name having different number of arguments is
called polymorphism. Is also called as function overloading.
Q) Does Java support operator overloading?
Operator overloading is not supported in Java.
Q) Encapsulation?
Group of Data & functions are said to be an Encapsulation with single entity.
Objects should not be allowed to access the properties of class instead could have
separate methods thru which the property can be accessed.
Q) Interface?
Interfaces are a collection of method prototypes, the implementation of which has
to be done by a class that inherits it. When it is declared as public, any class can
use the interface. Once an interface3 has been defined, any classes can implements
that interface.
Interfaces are javas substitute for multiple inheritances.
Interfaces can be extended.
One interface can inherit another by use of keyword extends.
When a class implements an interface that inherits another interface, it must
provide implementations for all methods defined within the interface chain.
CORE JAVA INTERVIEW QUESTIONS
Q) Different Data types in Java.
Byte 8 bit (are esp. useful when working with a stream of data from a
network or a file).
Short 16 bit
Char 16 bit Unicode
Int 32 bit (whole number)
Float 32 bit (real number)
Long 64 bit (Single precision)
Double - 64 bit (double precision)
Note: Any time you have an integer expression involving bytes, shorts, ints and
literal numbers, the entire expression is promoted to int before the calculation is
done.
Q) What is Unicode?
Java uses Unicode to represent the characters. Unicode defines a fully international
character set that can represent all of the characters found in human languages.
Q) What is Literals?
A literal is a value that may be assigned to a primitive or string variable or passed
as an argument to a method.
Q) Dynamic Initialization?
Java allows variables to be initialized dynamically, using any expression valid at the
time the variable is declared.
Q) What is Type casting in Java?
To create a conversion between two incompatible types, you must use a cast. There
are automatic casting and explicit casting.
Q) Arrays?
An array is to store the group of like-typed variables that are referred to by a
common name.
Q) Explain about BREAK stmt in java?
In Java, the break stmt has 3 uses.
First, it terminates a statement sequence in a switch statement.
Second, it can be used to exit a loop
Third, it can be used as go to keyword
Q) What are Constructors?
Constructors are special methods belonging to a class. These methods are basically
used to do initialization of instance variables. They are automatically called
whenever an instance of a class is created.
Q)THIS keyword?
The THIS keyword is a reference to the current object which is automatically
created.
Q) Garbage collection in java?
Since objects are dynamically allocated by using the new operator, java handles the
de-allocation of the memory automatically when no references to an object exist for
a long time is called garbage collection.
Q) Use of finalize() method in java?
FINALIZE () method is used to free the allocated resource.
Q) Explain ways to pass the arguments in Java?
In java, arguments can be passed in 2 ways,
Pass by value Changes made to the parameter of the subroutines have no effect
on the argument used to call it.
Pass by reference Changes made to the parameter will affect the argument used
to call the subroutine.
Q) Explain SUPER in Java?
First calls the superclass constructor.
Second, is used to access a method of the superclass that has been hidden by a
member of a subclass.
A subclass can call a constructor method defined by its super class by using super
(parameter-list). Super must always be the first statement.
Q) What is a Object class?
This is a special class defined by java; all other classes are subclasses of object
class. Object class is superclass of all other classes. Object class has the following
methods
objectClone () to creates a new object that is same as the object being cloned.
boolean determines whether one object is equal to another.
finalize called before an unused object is recycled.
toString () returns a string that describes the object.
Q) What are Packages?
Package is group of multiple classes under one name space.
Q)What is the difference between import java.utilDate and java.util.* ?
The star form may increase the compilation time especially if you import several
packages. However it doesnt have any effect run-time performance.
Q) Why cant I do myArray.length () ? Arrays are just objects, right?
Yes, the specification says that arrays are object references just like classes are.
You can even invoke the methods of Object such as toString () and hashCode () on
an array. However, length is a data item of an array and not a method. So you
have to use myArray.length.
Q) How can I put all my classes and resources into one file and run it?
Use a JAR file. Put all the files in a JAR, then run the app like this:
Java -jar [-options] jarfile [args...]
Q) Can I declare a data type inside loop in java?
Any Data type declaration should not be inside the loop.
Q) Advantage over jdk 1.0 vs. jdk 1.1 ?
Jdk1.1 release consists of Java Unicode character to support the multiple language
fonts, along with Event Handling, Java security, Java Beans, RMI, SQL are the
major feature provided.
Q) java.lang.* get imported by default. For using String and Exception
classes, you dont need explicitly to import this package. The major classes
inside this package are
Object class
Data type wrapper classes
Math class
String class
System and Runtime classes
Thread classes
Exception classes
Process classes
Class classes
Q) Arrays can be defined in different ways. All ways are right.
1
2
3
4
5
6
7
int arr[] = null;

int arr[][] = new int arr[][];

int [][] arr = new arr [][];

int [] arr [] = new arr[][];
Q) What is static method means?
When a member is declared as Static, it can be accessed before any objects of its
class are created, and without references to any object.
It allocates the memory once and uses the same until the end of the class.
Note: It is illegal to refer to any instance variable inside of a static method.
Q) Use of final keyword in Java?
Final methods mean methods cannot be override by any other method.
Final variable means constant, the value of the variable cant be changed, its
fixed.
Final class Means cant be inherited to other class. This type of classes will be
used when application required security or someone dont want that particular
class.
EXCEPTION HANDLING IN JAVA INTERVIEW QUESTIONS
Q) Exceptions are defined in which java package? OR which package has
definitions for all the exception classes?
Java.lang.Exception
This package contains definitions for Exceptions.
Q) What is throw keyword in exception handling?
throw keyword is used to throw the exception manually. While creating user defined
exception you would be needing to use throw keyword.
Q) Can static block throw exception?
Yes, A static block can throw exceptions. It has its own limitations: It can throw
only Runtime exception(Unchecked exceptions), In order to throw checked
exceptions you can use a try-catch block inside it.
Q) throw & throws statement?
Throwing an exception, in its most basic form is simple. You need to do two things.
First, you create an instance of an object that is a subclass of java.lang.Throwable.
Next you use the throw keyword to actually throw the exception.
If you write a method that might throw an exception (and this includes un-handled
exceptions that are generated by other methods called from your method), then
you must declare the possibility using a throws statement.
Q) Different Exception types?
Checked exceptions describes problems that can arise in a correct program,
typically difficulties with the environment such as user mistakes or I/O problems.
These exceptions are not a programming error, rather more likely with the
Environment behavior. Java.lang.Exception is the class used.
Unchecked exception Exception, which occurs at the runtime, is called
Unchecked exception. Java.lang.RuntimeException class is used. Runtime exception
describes the program bugs. Such exceptions arise from things like out-of-bounds a
correctly coded program would avoid array access, Database connection,
MalformedURLException, EOFException, NullPointerException, IllegalState Exception
etc and normally this.
Q) Interview questions about exception class
The Exceptions classes are derived from Throwable class. The structure is
given below.
Java.lang.Throwable class
Java.lang.Exception (Checked Exception)
Java.lang.RuntimeExceptions (Unchecked Exception).
Java.lang.Error
ArrayBoundOutOfException Whenever an array is referenced outside its
boundary.
NumberFormatException When we try Illegal operation with any data types.
For e.g., performing arithmetic on String variable.
NullPointerException When the Dynamic Variable carries value as null during
the condition will result in null pointer exception.
ClassCastException Attempting to use a reference as if it referred to an object
of some class but it doesnt
EmptyStackException Tried to pop or peek from an empty stack
IllegalStateException A method was activated when the object was in a state
that violates the methods precondition.
NegativeArraysizeException Allocating an array with a negative number of
components
IOException An input or output error
Q) finally block?
Irrespective of success or failure of try/catch block, the finally block gets execute.
Finally block will best utilized to close your open database connections, open files
etc.
JAVA I/O INTERVIEW QUESTIONS
Q) Write a Small program to read an input from command prompt ?
1
2
3
4
5
6
7
8
9
10
11
12
13
Public class ClassName{
public static void main(String a[])
try{
char ch = (char) system.in.read();
if (Character.isJavaIdentifiedPart(ch);
System.out.println( is a Identifier);
if (Character.isJavaIdentifiedStart(ch);
System.out.println(can be start of Identifier);
}catch(Exception e){
System.out.println(e);
}
}
}
Points to remember: Math is a final class. Cannot be override. It can imported
from java.lang.*. All the methods( ceil(), floor(), rint(), round(), random() ) in this
class are static and they can be invoked automatically.
An only double data type is the input for math methods.
Q) List of classes under java.util. *?
This package contains the basic classes, which form as a javas data structure.
Since java doesnt support Structures, Unions, and Pointers as in c++, hence this
package is used.
Vector is for growable array. It allows storing different objects of any type.
StringTokenizer Generating tokens for a given string based on delimiter.
Stack LIFO, FIFO
Date - is depreciated in jdk 1.1, 1.2, use Calendar in-spite
Calender System data and calendar
Enumeration hasMoreElements(); nextElement()
Hashtable Key value pair.
Q) Wrapper Classes?
Vector and Stack classes allow operation only for object not for data types. Hence
some of the data types are wrapped to convert them into object to put into vector.
Such data type wrapper classes are
Integer, Double, Float, Character etc.
For e.g.
1
2
3
4
Vector v = new Vector();
int I = 5; //this cant be added to vector hence need to wrap
Integer ii = new Integer(I);
v.addElement(ii);
Q) Different methods can operates on Vector are
1
2
3
4
v.elementAt(int);
v.insertElementAt(object, int);
removeElementAt(int);
removeAllElements();
Q) Hashtable ?
Hashtable are used to store key and value pair. User need not to worry about
whether the variable is stored rather we just need to know the key retrieve the
corresponding value.
Hashtable h1 new Hashtable();
Methods are :
1
2
3
4
5
6
7
8
9
10
11
12
h1.put(key,value);
h1.get(key);

Sample program to find out the list of all keys from hastable.

1
Enumeration e = h1.keys();
While (e.hasMoreElements())
{
object obj = e.nextElement();
h1.get(obj);
}
Go through all the
Basic Arithmetic operators like (+, -, *, /, %, ++, --, += ).
Boolean logical operators like (&amp;, |, ^, ||, &amp;&amp; )
The ? Operator (ternary operator).
Shift operators (&gt;&gt;, &lt;&lt;, &gt;&gt;&gt;). Very important.
Q) How do I resize an array?
You can't resize an array. Once an array is created, you will not be able to change
the length of it. You can allocate a new array, copy the elements into the new
array, and set the reference to the original array to point to the new array -
1
2
3
4
ABC[] arr = new ABC[];
// Below I'm creating a new array with larger size
XYZ[] newarr = new XYZ[5];
System.arraycopy(arr, 0, newarr, 0, arr.length);
arr = newarr;
5
Q) What is a Java Bean?
A JavaBean is a Java class that follows some simple conventions including
conventions on the names of certain methods to get and set state called
Introspection. Because it follows conventions, it can easily be processed by a
software tool that connects Beans together at runtime. JavaBeans are reusable
software components.
APPLET INTERVIEW QUESTIONS
Q) How do you do file I/O from an applet?
Unsigned applets are simply not allowed to read or write files on the local file
system .
Unsigned applets can, however, read (but not write) non-class files bundled with
your applet on the server, called resource files
Q) What is container ?
A component capable of holding another component is called as container.
Container
Panel
Applet
Window
Frame
Dialog
Learning)
1. Flow Layout is default for panel.
2. Border Layout is default for Frames.
Q) On Windows, generally frames are invisible, how to make it visible. ?
1
2
3
Frame f = new Frame();
f.setSize(300,200); //ht and width
f.setVisible(true) ; // Frames appears
Q) JFC Java Foundation Class
Swing
AWT
Java2D
Drag and Drop
Accessibility
Learning) Listeners and Methods?
ActionListerner - actionPerformed();
ItemListerner - itemStateChanged();
TextListener - textValueChanged();
FocusListener - focusLost(); & FocusGained();
WindowListener
- windowActified(); windowDEactified(); windowIconified(); windowDeiconified();
windowClosed(); windowClosing(); windowOpened();
MouseMotionListener - mouseDragged(); & mouseMoved();
MouseListener
- mousePressed(); mouseReleased(); mouseEntered(); mouseExited(); mouseClick
ed();
Learnings)
parseInt to convert string to int.
getBytes string to byte array
Q) Applet Life cycle?
Following stage of any applets life cycle, starts with init(), start(), paint(), stop()
and destroy().
Q) showStatus() ?
To display the message at the bottom of the browser when applet is started.
Q) What is the Event handling?
Is irrespective of any component, if any action performed/done on Frame, Panel or
on window, handling those actions are called Event Handling.
Q) What is Adapter class?
Adapter class is an abstract class.
Advantage of adapter: To perform any window listener, we need to include all the
methods used by the window listener whether we use those methods are not in our
class like Interfaces whereas with adapter class, its sufficient to include only the
methods required to override. Straight opposite to Interface.
Q) Diaglog can be modal, non-modal dialog.
Dialog d = new Dialog(this,Title,true) - 3
rd
parameter indicated whether dialog
frame is modal or non-modal.
Q) Handling keyboard events?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.awt.*, java.awt.event.*, java.applet.*;
public class CN extend Applet implements KeyListener {
String msg = :
int X= 10, Y =20;
public void init(){
addKeyListener(this);
requestFocus();
}

public void keyPressed(KeyEvent ke){
showStatus(Key Down);
}

public void keyReleased(KeyEvent ke){
showStatus(Key UP);
}

public void keyTyped(KeyEvent ke){
msg += ke.getKeyChar();
repaint();
}

public void paint(Graphics g){
g.drawString(msg,X,Y);
}
}
JAVA MULTITHREADING INTERVIEW QUESTIONS
Q) Thread?
In concurrent programs, several independent activities happen at the same time.
Java models this through an interface, Runnable that embodies generic activities
and a class, Thread that is responsible for the independent execution of Runnable.
Thread Life cycle: Starts with init(), start(), run(), stop() and destroy().
Learning) Other Thread methods
1. stop() kills the thread. (Different from Applet.stop().)
2. sleep(ms): non-busy wait for ms milliseconds, then throws
InterruptedExceptions.
3. setPriority(int pr): lowest = 1, highest = 10 , normal =5
4. yield(): signals its willingness to give up CPU. Control transferred
only when there is a ready thread of the same or higher priority.
5. wait() vs. notify()
6. suspend() vs. resume()
Q) Java Threads
1. interface Runnable
2. abstract class Thread
Two different ways to implement threads
Extends Thread class
1. create a subclass of Thread class
2. implement void run() method, which will be the main body of the
thread.
3. initiated by start(), and terminates when run() ends.
Implements Runnable interface
1. create a class implementing Runnable interface.
2. create a Thread instance inside the class (with this as an
argument).
3. invoke start() method.
4. initiated by creating the class instance, terminates when run()
ends.
Q) Synchronization?
I have good news and bad news for you. The bad news is that you can run into big
problems when two or more threads share parameters. Recall that the threads run
independently and re likely to interfere during complex operations.
One has to enforce proper synchronization between threads. In Java, synchronized
is a keyword applied to methods:
public synchronized void someMethod()
Each Java object has a lock. To execute synchronized code on an object, a thread
must own the object's lock. When two threads execute code synchronized on the
same object, only one of them acquires the lock and proceeds. The other is
paused until the first one releases the lock. Thanks to synchronization each thread
has a chance to use the object with no meddling from the other thread.
Learning) A thread that waits on an object is automatically woken up by
other threads calling notifyAll() on the same object. wait() is efficient and
consumes no CPU cycles. notify() is faster than notifyAll() but it can be
dangerous when several threads wait on the same object. In practice, it is
seldom used and I suggest you stick to the safer notifyAll().
If no result is available getResult() waits:
1
2
3
4
5
6
7
public synchronized Object getResult()
throws InterruptedException
{
while (result == null)
wait();
return result;
}
INTERVIEW QUESTIONS RELATED TO JAVA STRINGS?
Q) StringBuffer class ?
An instance of this class represents a string that can be dynamically modified. A
String buffer has a capacity, which is the maximum-length string it can represent
without needing to allocate more memory. A string buffer can grow beyond this as
necessary, so usually do not have worry about capacity.
Different methods are
1
2
3
StringBuffer sb = new StringBuffer(Planetasia);
sb.insert(3,xyz); // plaxyznetasia
sb.append(abc); // plaxyznetasiaabc
Q) Different methods operated on String?
String s1 = Planetasia;
String s2 = bangalore;
int i = 3;
s1.charAt(i); - will find the character at that position.
s1.indexOf(t); - will return the position of t in the string s1.
s1.lastIndexOf(a); - will return the position of a starting the index at the end.
s1.equals(s2) String s1 and s2 content will be compared, return true if they are
equal.
s1 == s2 - The reference of both the string will be compared.
s1.compareTo(s2) will compare 2 strings and result three possible value
0 if both the strings are equal.
> 1 - if s1 is greater than s2
< 1 - if s2 is greater than s1.
s1.endsWith, s1.startsWith, s1.equalsIgnoreCase.
Q) trim (). ?
Is a method used to remove the unwanted space in the beginning and end of the
variable?
Q) A small program on StringTokenizer -
1
2
3
4
5
public class CN
{
public static void main(String a[]){
String s = "Java in two days" ;
StringTokenizer st = new StringTokenizer(s, );
int I = st.countToken();
6
7
8
9
10
11
12
13
while(st.hasMoreTokens(I))
{
String y = st.nextToken();
System.out.println(y);
}
}
}
Q) What is the difference between String s = abc; and String s = new
String(abc); ?
As such no big difference, but second statement will take extra memory allocation.
JDBC(JAVA TO DATABASE CONNECTVITY) INTERVIEW QUESTIONS
Q) JDBC package contains a set of classes and methods for issuing SQL
stmt, table update and calls to stored procedure.
Java Application ---jdbc api--------- JDBC driver Manager ----uses JDBC driver Api
to load--- JDBC Driver protocol DB
Q) Java Soft has defined 4 types of drivers to connect with db thru DB
driver?
Type 1 JDBC-OBDCBridge
Type 2 - Native-API-Partly-Java driver
Type 3 - JDBC-Net-All-Java driver
Type 4 - Native Protocol-All-Java driver
Q) 3 classes for sending sql stmts to DB thru connection object.
Statement created by method createStatement(). A statement object is used to
sending simple sqls.
PreparedStatement method prepareStatement() uses. It has potential &
efficient than a statement object becoz it has been pre-compiled and stored it for
future use.
CallableStatement - are used to execute the SQL stored procedures.
Q) The statement interface provides 3 different methods for executing SQL
stmts, what are those?
executeQuery() Queries like select.
executeUpdate() Queries like insert, update, delete and also for DDL
execute() - it returns boolean. If true means all select query is operated, if it
false DML queries have taken place.
Q) What is Connection in JDBC?
A connection object represents a connection with a database. A connection session
includes SQL stmts that are executed and the results are returned over that
connection. A single application can have more connection with a single DB.
Opening a connection is established with a db to call method
DriverManager.getConnection().
Template to create connection on to database located at URL : jdbc:odbc:wombat
1
2
String Url = "jdbc:odbc:wombat";
Connection con = DriverManager.getConnection(Url,"username","password");
TEST YOUR SKILLS - GUESS THE ANSWERS OF JAVA PROGRAMS - FOR WRITTEN
TESTS AS WELL AS TO SHARPEN THE JAVA KNOWLEDGE
Question - What is o/p of following program?
1
2
3
4
5
6
7
8
9
10
11
12
public class Test
{
public static void main(String args[])
{
int num = 132;
List ls = new ArrayList();
ls.add(new Object());
ls.add("Welcome");
ls.add(num);
System.out.println(ls.get(1));
}
}
a) Welcome
b) It will give a Compilation Error!!
c) Runtime Error will occur
d) 132
Ans is (a)
Welcome gets printed since it is the 2nd object(String object) in the list and
ArrayList index starts from 0.
Question - What is o/p of following program?
1
2
3
4
5
6
public class FClass {
private int final FNUM;
public static void main(String args[]){
System.out.println(new FClass().FNUM);
}
}
a) 1
b) 0
c) RunTimeException
d) Compile time error.
Ans is (d). private final variable FNUM needs to be initialized (should have some
value assigned) since its declared final.
Question - Select methods that correctly overload the following method
1 byte sampMethod(short i) throws Exception {...}
a) int sampMethod(int i) throws IOException{...}
b) protected int sampMethod(short shr) throws FileNotFoundException{...}
c) private String sampMethod(byte byt,short shr) throws Exception{...}
d) char sampMethod(String str) throws RuntimeException{...}
e) int sampMethod(short shr){...}
Ans is (a),(c)& (d)
Question -
1
2
3
4
5
6
public class MyClass
{
public static void main(String[] args)
{
int[] myArr = new int[]{0,1,2,3,4,5};
System.out.println(myArr[0]+ myArr[5]+myArr[2]);
}
7
8
}
a) 032
b) It will throw a Compilation Error!!
c) 7
d) 172
Ans is (c).
Hint: Array(myArr) index starts from 0.
Question - Will this code compile fine?
1
2
3
4
5
6
7
8
public class final HMap {
private static final Map m = new HMap();
public static void main(String[] args) {
m.put("p1","v1"); //line num:3
m.put("p2","v2");
m = new HMap(); //line num:5
}
}
a) Yes
b) No, Compilation Error at line 3
c) No, Runtime Error
d) No, Compilation Error at line 5
Ans is (d). Once declared the final variable cannot be initialized again.
Question -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.*;
class Demo
{
Demo() throws IOException
{
throw new IOException();
}
}

class test1 extends Demo
{
public static void main(String a[]) throws Exception
{
try
{
test1 aObj = new test1();
}
catch(Exception io)
{
System.out.println("Catch2");
}
}

test1() throws Exception,ClassCastException
{
try{
System.out.println("constructor");
25
26
27
28
29
30
31
32
33
34
}
catch(Exception io)
{
System.out.println("Catch1");
}
}
}
What is output?
1. Catch1
2. Catch2
3. Compilation Fail.
4. Runtime Exception
5. Code runs fine with No output
Ans is (2).
Question -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Demo
{
int inum = 10;
}
class Sample extends Demo
{
int inum = 15;
public static void main(String[] args)
{
Sample obj1 = new Sample();
Demo obj2 = new Sample();
System.out.println(obj1.inum);
System.out.println(obj2.inum);
System.out.println(((Demo)obj1).inum );
}
}
1. 15 10 15
2. 15 15 15
3. 10 10 10
4. 15 10 10
5. 10 15 104
6. Compilation Fails.
7. Runtime Exception.
Ans: (4).
Question -
1
2
3
4
class Test
{
public static void main(String[] args)
{
5
6
7
8
9
byte byt1 = -128;
byte byt2 = 128;
System.out.println(byt1+byt2);
}
}
1. 0
2. 1
3. -1
4. Compilation Fails.
5. Runtime Exception
Ans: (4)
Question -
1
2
3
4
5
6
7
8
9
public class A
{
public static void main(String a[])
{
byte byt1 = 1 , byt2 =2, res;
res = byt1 + byt2--;
System.out.println("Ans :"+res);
}
}
1. 0
2. 1
3. 2
4. 3
5. Compilation Fails.
6. Runtime Exception
Ans: (5)
1
2
3
4
5
6
7
8
9
public class A
{
public static void main(String a[])
{
short shr = 2;
int num = shr++ - shr++;
System.out.println(""+num++ + shr);
}
}
1. 0
2. 1
3. -14
4. -13
5. 3
6. 4
Ans: (3)
Question -
1
2
public class A
{
3
4
5
6
7
8
9
public static void main(String a[])
{
int i = 1;
for(;;){}
System.out.println("Hello world");
}
}
Ans: Compilation error. For(;;) forms an Infinite loop
Question - Which of the following are not valid ?
1. String String;
2. Integer Integer;
3. Double Object;
4. int main;
5. int unsigned;
Ans: Nothing is INVALID
Question -
1
2
3
4
5
6
7
8
9
public class Sample
{
int inum = 1;
public static void main(String a[])
{
int inum = 12;
System.out.print( this.inum );
}
}
Ans: inum is a non-static variable, this cannot be referenced from a static context
Question -
1
2
3
4
5
6
7
8
9
10
11
12
13
public class A extends A1,A2 //Line no: 1
{
public static void main(String a[])
{
System.out.println("Hi");
}
}

interface I extends I1,I2 {} //Line no: 2
interface I1{}
interface I2{}
class A1{}
class A2{}
1. Runs Fine
2. Compilation Error at Line no: 1
3. Compilation Error at Line no: 2
4. Compilation Error at Line 1 and Line 2.
5. Runtime Exception
Ans: (4)
Question -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Demo
{
static String myMethod(int i)
{
return "int";
}
static String myMethod(float i)
{
return "float";
}
public static void main (String[] args)
{
long num1 = 1;
double num2 = 2;
System.out.print(myMethod(num1)+","+ myMethod(num2));
}
}
What is the Result ?
1. Prints: float,double
2. Prints: float,float
3. Prints: double,float
4. Compile-time error
5. None of the above
Ans: (4)
Question -
1
2
3
4
5
6
7
8
9
10
11
class XYZ
{
{
System.out.println("initializer");
}
public static void main(String a[])
{
System.out.println("hello");
XYZ obj=new XYZ();
}
}
What is the Result ?
1.prints hello and initializer
2.prints initializer and hello
3.compile time error
4.runtime error
5.None of the above
Ans: (1)
Question -
1
2
3
class bike { }
class Demo extends bike
{
4
5
6
7
8
9
10
11
12
public static void main(String[] args)
{
Demo[] a1=new Demo[2];
bike[] a2;
a2=a1; //Line no:3
Test[] a3;
a3=a1; //Line no:5
}
}
What is the Result ?
1. compile time error at line 3
2. compile time error at line 5
3. Runtime exception
4. The code runs fine
5. None of the above
Ans: (4)
Question -
1
2
3
4
5
6
7
8
9
10
11
12
class Test
{
static interface I //Line no:1
{
static class Test2{} //Line no:2
}
public static void main(String a[])
{
Test.I.Test2 ob1=new Test.I.Test2(); //Line no:3
System.out.println("object created");
}
}
What is the Result ?
1. Print object created.
2. Compilation Error at line 1.
3. Compilation Error at line 2.
4. Compilation Error at line 3.
5. Runtime Exception
6. None of the above
Ans: (1)
Question -
1
2
3
4
5
6
7
8
9
public static void parse(String str)
{
try
{
float f = Float.parseFloat(str);
}
catch (NumberFormatException nfe)
{
f = 0;
}
10
11
12
13
14
15
16
17
18
19
20
finally
{
System.out.println(f);
}
}

public static void main(String[] args)
{
parse("invalid");
}
What is the result?
1. 0.0
2. 0
3. Compilation fails.
4. NumberFormatException is thrown at runtime.
5. ParseException is thrown at runtime.
Ans: (3)
Question -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MyThreadClass implements Runnable
{
public void run()
{
System.out.print("thread is running");
}
public static void main(String[] args)
{
Thread th = new Thread(new MyThreadClass());
th.run();
th.run();
th.start();
}
}
What is the result?
1. Compilation fails.
2. An exception is thrown at runtime.
3. The code executes and prints "thread is running".
4. The code executes and prints "thread is runningthread is running".
5 The code executes and prints "thread is runningthread is runningthread is
running".
Ans: (5)
Question -
Which modifiers would be valid in the declaration of a main() method so that the
class can be run from command line?
Can select multiple options.
1.native
2.protected
3.public
4.final
5.abstract
Ans: (3), (4)
Question -
Which of the following class can not be extended ?
1. Object
2. Thread
3. Error
4. Exception
5. Throwable.
6. String
Ans: (6)
What is Inheritance in Java Programming?
by Chaitanya Singh
in OOPs Concept
Inheritance in java is one of the essential feature of Object-Oriented
Programming (OOP). Inheritance allows a class to use the properties and methods
of another class. In other words, the derived class inherits the states and behaviors
from the base class. The derived class is also called subclass and the base class is
also called superclass. The derived class can add its own additional variables and
methods. These additional variable and methods differentiates the derived class
from the base class.
Inheritance is a compile-time mechanism. A superclass can have any number of
subclasses. But a subclass can have only one superclass. This is because Java does
not support multiple inheritance.
I have covered Inheritance in detail at one of my Post: OOPs Concepts in Java.
The superclass and subclass have is a relationship between them. Lets have a
look at the example below.
INHERITANCE IN JAVA PROGRAMMING
Lets consider a superclass Vehicle. Different vehicles have different attributes but
there are a few attributes which are common to all. Speed, color, fuel used, size are
some of them. Hence we can create a class Vehicle with states and actions that
are common to all vehicles. The subclass of this superclass can be any type of
vehicle. Example, Car. A Car has all the features of a vehicle. But it has its own
attributes which makes it different from other subclasses. By using inheritance we
need not rewrite the code that weve already used with the Vehicle. The subclass
can also be extended. We can make a class Sports Car which extends Car. It
inherits the features of both Vehicle and Car.
The keyword used for inheritance is extends. The syntax is as given below.
1
2
3
public class extends {
// derived class methods extend and possibly override
}
Here is a simple example to illustrate the use of inheritance in Java.
1
2
3
// A class to display the attributes of the vehicle
class vehicle {
String color;
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
int speed;
int size;
void attributes() {
System.out.println("Color : " + color);
System.out.println("Speed : " + speed);
System.out.println("Size : " + size);
}
}

// A subclass which extends for vehicle
class car extends vehicle {
int CC;
int gears;
void attributescar() {
// The subclass refers to the members of the superclass
System.out.println("Color of Car : " + color);
System.out.println("Speed of Car : " + speed);
System.out.println("Size of Car : " + size);
System.out.println("CC of Car : " + CC);
System.out.println("No of gears of Car : " + gears);
}
}
public class Test {
public static void main(String args[]) {
car b1 = new car();
b1.color = "Blue";
b1.speed = 200 ;
b1.size = 22;
b1.CC = 1000;
b1.gears = 5;
b1.attributescar();
}
}
The output is
Color of Car : Blue
Speed of Car : 200
Size of Car : 22
CC of Car : 1000
No of gears of Car : 5
Note:
The derived class inherits all the members and methods that are declared as public
or protected. If declared as private it can not be inherited by the derived classes.
The private members can be accessed only in its own class. The private members
can be accessed through assessor methods as shown in the example below. The
derived class cannot inherit a member of the base class if the derived class declares
another member with the same name.
PFB inheritance in java with example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// A class to display the attributes of the vehicle
class vehicle {
String color;
private int speed;
private int size;
public int getSize() {
return size;
}
public int getSpeed() {
return speed;
}
public void setSize(int i) {
size = i;
}
public void setSpeed(int i) {
speed = i;
}
}

// A subclass which extends for vehicle
class car extends vehicle {
int CC;
int gears;
int color;
void attributescar() {
// System.out.println("Speed of Car : " + speed); // Error due to access
violation
// System.out.println("Size of Car : " + size); // Error due to access
violation

}
}
public class Test {
public static void main(String args[]) {
car b1 = new car();
b1.color = 500; // the subclass can inherit 'color' member of the
superclass
b1.setSpeed(200) ;
b1.setSize(22);
b1.CC = 1000;
b1.gears = 5;

// The subclass refers to the members of the superclass
System.out.println("Color of Car : " + b1.color);
System.out.println("Speed of Car : " + b1.getSpeed());
System.out.println("Size of Car : " + b1.getSize());
System.out.println("CC of Car : " + b1.CC);
System.out.println("No of gears of Car : " + b1.gears);

}
47
48
}
The output is
Color of Car : 500
Speed of Car : 200
Size of Car : 22
CC of Car : 1000
No of gears of Car : 5
TYPES OF INHERITANCE IN JAVA
Read my below post to understand Simple, Multiple, Multilevel and hybrid
inheritance. You would also be able to know why java doesnt support Multiple
inheritance.
Read more at: Types of inheritance in Java
CONSTRUCTORS AND INHERITANCE IN JAVA
The constructor in the superclass is responsible for building the object of the
superclass and the constructor of the subclass builds the subclass part. When a
constructor of the subclass is defined, the default superclass constructor will be
called implicitly. Hence, under inheritance the objects are constructed top-down.
The superclass constructor can be called explicitly using the keyword super, but it
should be first statement in a constructor. The keyword super always refers to the
superclass immediately above the calling class in the hierarchy. The use of multiple
supers to access an ancestor class other than the direct parent is illegal.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class shape {
private int length;
private int breadth;
public int getBreadth() {
return breadth;
}

public int getLength() {
return length;
}
public void setBreadth(int i) {
breadth = i;
}
public void setLength(int i) {
length = i;
}

// default Constructor
shape() {
length = 0;
breadth = 0;
System.out.println("Inside default constructor of Shape ");
}

// Parameterized Constructor
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
shape(int len, int bdth) {
length = len;
breadth = bdth;
System.out.println("Inside constructor of Shape ");
System.out.println("length : " + length);
System.out.println("breadth : " + breadth);
}
}

// A subclass which extends for shape
class rectangle extends shape {
private String type;

// default Constructor
rectangle() {
super();
type = null;
System.out.println("Inside default constructor of rectangle ");
}

// Parameterized Constructor
rectangle(String ty, int len, int bdth) {
super (len, bdth);
System.out.println("Inside constructor of rectangle ");
System.out.println("length : " + len);
System.out.println("breadth : " + bdth);
System.out.println("type : " + type);
}

public String getType() {
return type;
}

public void setType(String string) {
type = string;
}
}

// A subclass which extends for rectangle
class coloredRectangle extends rectangle {
private String color;
/* default Constructor*/
coloredRectangle() {
super();
color = null;
System.out.println("Inside default constructor of coloredRectangle ");
}

// Parameterized Constructor
coloredRectangle(String c, String ty, int len, int bdth) {
super (ty, len, bdth);
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
System.out.println("Inside constructor of coloredRectangle ");
System.out.println("length : " + len);
System.out.println("breadth : " + bdth);
System.out.println("type : " + ty);
}
public String getColor() {
return color;
}
public void setColor(String string) {
color = string;
}
}

public class Test {
public static void main(String args[]) {
coloredRectangle CR = new coloredRectangle();
coloredRectangle CR2 = new coloredRectangle("Red","Big", 5, 2 );
}
}
The output is:
Inside default constructor of Shape
Inside default constructor of rectangle
Inside default constructor of coloredRectangle
Inside constructor of Shape
length : 5
breadth : 2
Inside constructor of rectangle
length : 5
breadth : 2
type : null
Inside constructor of coloredRectangle
length : 5
breadth : 2
type : Big
METHOD OVERRIDING
A method from the superclass can be redefined in the subclass. The new method in
the subclass will have the same return type, method name and number and type of
parameters. This is called method overloading. This new method will have a
different definition in the derived class. If it has different number and type of
parameters then it is called method overloading.
The access specifier can allow more access in the overriding method. But it can not
reduce the access. Example, a protected method can be made public in the
subclass but cannot be made private.
By using super we can access the overridden method in the super class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class shape {
private int length;
private int breadth;
// default Constructor
shape() {
length = 0;
breadth = 0;
}
// Parameterized Constructor
shape(int len, int bdth) {
length = len;
breadth = bdth;
}
void showattributes() {
System.out.println("length : " + length);
System.out.println("breadth : " + breadth);
}
}

// A subclass which extends for shape
class rectangle extends shape {
private String type;
/* default Constructor
*/
rectangle() {
type = null;
}
// Parameterized Constructor
rectangle(String ty, int len, int bdth) {
super(len,bdth);
type = ty;
}
void showattributes() {
super.showattributes(); // showattributes() in shape is called
System.out.println("type : " + type);
}
}

public class Test {
public static void main(String args[]) {
rectangle rect = new rectangle("Blue",5,7);
rect.showattributes(); // showattributes() in rectangle is called
}
}
43
44
The output is :
length : 5
breadth : 7
type : Blue
Method overriding is the basis of dynamic method dispatch which is one of Javas
most powerful concepts. Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at the run time and not at compile time.
This is how run-time polymorphism implemented in Java. When an overridden
method is called, the type of object being referred to decide which version of the
method will be executed. This is done at the run-time. Overridden methods are
another way of implementing one interface, multiple methods aspect of
polymorphism in java.
ABSTRACT CLASSES
The superclasses are more general than their subclasses. Usually, the superclasses
are made abstract so that the objects of its prototype cannot be made. So the
objects of only the subclasses can be used. To make a class abstract, the keyword
abstract is used in the class definition.
Abstract methods are methods which do not have method statements. The
subclasse provides the method statements. The methods provided by the
superclass needs to be overridden by the subclass. The class that has at least one
abstract method should be made abstract. The abstract class can not be
instantiated because it does not define a complete implementation.
1
2
3
public abstract class {
.
}
Using Final with methods
We can prevent a method from being overridden by using the keyword final at the
start of its declaration.
Final methods can not be overridden.
The syntax is as given below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public abstract void methodname();

class shape {

final void showattributes() {
System.out.println("Inside class shape ");

}
}

// A subclass which extends for shape
class rectangle extends shape {

void showattributes() { // Cannot override the final method
System.out.println("Inside class rectangle");
15
16
17
}
}
The method showattributes() cannot be overridden in the class rectangle because it
is declared as final in class shape. It shows an error when we try to override it.
Using Final with class
We can also prevent inheritance by making a class final. When a class is declared
as final, its methods also become final. An abstract class cannot be declared as final
because an abstract class is incomplete and its subclasses need to provide the
implementation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
final class shape {

void showattributes() {
System.out.println("Inside class shape ");

}
}

/* A subclass which extends for shape
*/
class rectangle extends shape { // The type rectangle cannot subclass the
final class shape

void showattributes() {
System.out.println("Inside class rectangle");
}
}
The class shape cannot be inherited because it is declared as final. It will show an
error when we try to inherit it.
USING FINAL WITH DATA MEMBERS
A variable can be made constant by making the variable name final. The value of
the final variable cannot be changed throughout the lifetime of the program, but it
can be given an initial value. These variables can be accessed via an object of the
class in which they are declared. Also, they can be inherited by subclasses and
accessed inside those subclasses.
1
2
3
4
5
6
7
8
9
10
11
12
class employee {
final int empcode1 = 0;
final int empcode2 = 1;
final int empcode3 = 2;
final int empcode4 = 3;
String empname [] = {
"ABC",
"DEF",
"GHI",
"JKL"
};
String getempname(int i) {
if (i >= 0 & i < empname.length)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
return empname[i];
else
return "Invalid Employee Number";
}
}
public class Test {
public static void main(String args[]) {
employee emp = new employee();
System.out.println(emp.getempname(emp.empcode1));
System.out.println(emp.getempname(emp.empcode2));
System.out.println(emp.getempname(emp.empcode3));
System.out.println(emp.getempname(emp.empcode4));
}
}
Out put is:
ABC
DEF
GHI
JKL
Target Keywords: Inheritance in OOPS, Inheritance in Java, java inheritance
example
Reference
Java 2: the complete reference: fifth Edition
http://java.sun.com
Polymorphism in Java Method Overloading and Overriding
by Chaitanya Singh
in OOPs Concept
In the last tutorial I shared about Java Inheritance and in this tutorial I will discuss
about Polymorphism in java. Java is an Object Oriented Programming (OOPs)
language. Polymorphism is one of the key point in OOPs concepts.
WHAT IS POLYMORPHISM IN PROGRAMMING
Polymorphism is the capability of a method to do different things based on the
object that it is acting upon. In other words, polymorphism allows you define one
interface and have multiple implementations.
It is a feature that allows one interface to be used for a general class
of actions.
An operation may exhibit different behavior in different instances.
The behavior depends on the types of data used in the operation.
It plays an important role in allowing objects having different internal
structures to share the same external interface.
Polymorphism is extensively used in implementing inheritance.
In Java, the concept of polymorphism is achieved through:
1) Method Overloading
2) Method Overriding
Method Definition:
A method is a set of code which is referred to by name and can be called (invoked)
at any point in a program simply by utilizing the methods name.
1) Method Overloading:
In Java, it is possible to define two or more methods in a class, with the same
name and the arguments or parameters should be different. This is known as
Method Overloading.
I have covered method overloading and Overriding below. To know more about
polymorphism types refer my post Types of polymorphism in java: Static, Dynamic,
Runtime and Compile time Polymorphism.
1) POLYMORPHISM IN JAVA: METHOD OVERLOADING
1. To call an overloaded method in Java, it is must to use the type
and/or number of arguments to determine which version of the
overloaded method to actually call.
2. Overloaded methods may have different return types; the return
type alone is insufficient to distinguish two versions of a method. .
3. When Java encounters a call to an overloaded method, it simply
executes the version of the method whose parameters match the
arguments used in the call.
4. It allows the user to achieve compile time polymorphism.
5. An overloaded method can throw different exceptions.
6. It can have different access modifiers.
java polymorphism tutorial example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Overload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
24
25
26
27
System.out.println("O/P : " + result);
}
}
Here the method demo() is overloaded 3 times with 1 integer parameter, 2 integer
parameter and a double. The methods are invoked or called with the same type and
number of parameters used.
Output:
a: 10
a and b: 10, 20
double a: 5.5
O/P : 30.25
RULES FOR METHOD OVERLOADING
1. Overloading can take place in the same or in its sub-class.
2. Constructor in Java can be overloaded
3. Overloaded methods must have a different argument list.
4. Overloaded method should always be in part of the same class,
with same name but different parameters.
5. The parameters may differ in their type or number, or in both.
6. They may have the same or different return types.
7. It is also known as compile time polymorphism.
2) POLYMORPHISM IN JAVA: METHOD OVERRIDING
The derived class which is extended from the base class has a method which is
exactly similar to the one present in the base class. This is called as overriding a
method.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class BaseClass
{
Public void methodToOverride() //Base class method
{
System.out.println ("I'm the method of BaseClass");
}
}

public class DerivedClass extends BaseClass
{
Public void methodToOverride() //Derived Class method
{
System.out.println ("I'm the method of DerivedClass");
}
}

public class TestMethod
{
Public static void main (String args []) {
BaseClass obj1 = new BaseClass(); // BaseClass reference and object
19
20
21
22
23
24
25
BaseClass obj2 = new DerivedClass(); // BaseClass reference but
DerivedClass object
obj1.methodToOverride(); // Calls the method from BaseClass class
obj2.methodToOverride(); //Calls the method from DerivedClass class
}
}
Output:
Im the method of BaseClass
Im the method of DerivedClass
RULES FOR METHOD OVERRIDING:
1. applies only to inherited methods
2. object type (NOT reference variable type) determines which
overridden method will be used at runtime
3. Overriding methods must have the same return type
4. Overriding method must not have more restrictive access modifier
5. Abstract methods must be overridden
6. Static and final methods cannot be overridden
7. Constructors cannot be overridden
8. It is also known as Runtime polymorphism.
USING THE SUPER KEYWORD:
When invoking a superclass version of an overridden method the super keyword is
used.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Vehicle {

Public void move () {
System.out.println ("Vehicles are used for moving from one place to
another ");
}
}

class Car extends Vehicle {
Public void move () {
Super. Move (); // invokes the super class method
System.out.println ("Car is a good medium of transport ");
}
}

public class Test Car {
Public static void main (String args []){
Vehicle b = new Car (); // Vehicle reference but Car object
b.move (); //Calls the method in Car class
}
}
20
Output:
Vehicles are used for moving from one place to another
Car is a good medium of transport
Encapsulation in Java
by Chaitanya Singh
in OOPs Concept
I have already discussed about encapsulation in brief in my article OOPs concepts.
Also, I covered Java polymorphism and Java inheritance in separate articles. Here I
will coverJava encapsulation in detail.
WHAT IS ENCAPSULATION?
Encapsulation means the localization of the information or knowledge within an
object. In other words you can say that Using this technique data can be
hidden. but how?? If a data member is private which means it can only be
accessed within the same class. No outside class can access private data member
(variable) of other class. This way data can be accessed by public methods of the
same class and would not be accessed outside the class. Thats the reason
encapsulation is known as data hiding.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class EncapsDemo{
private int ssn;
private String empName;
private int empAge;

public int getEmpSSN(){
return ssn;
}

public String getEmpName(){
return name;
}

public int getEmpAge(){
return age;
}

public void setEmpAge( int newValue){
empAge = newValue;
}

public void setEmpName(String newValue){
empName = newValue;
}

public void setEmpSSN( String newValue){
ssn = newValue;
}
}
public class EncapsTest{
29
30
31
32
33
34
35
36
37
38
39
public static void main(String args[]){
EncapsDemo obj = new EncapsDemo();
obj.setEmpName("Mario");
obj.setEmpAge(32);
obj.setEmpSSN("1111222233");
System.out.print("Employee Name: " + obj.getEmpName());
System.out.print("Employee SSN: " + obj.getEmpSSN());
System.out.print("Employee Age: " + obj.getEmpAge());
} }
Output:
Employee Name: Mario
Employee SSN: 1111222233
Employee Age: 32
you can see in above example that all the three data members are private which
gets accessed using private methods of local class. These variables will not be
accessible in any other class. Employee name, SSN and Age will become hidden
data members using encapsulation technique of OOPs.
Encapsulation is also called as Information Hiding.
1. Objects encapsulate data and implementation details. To the
outside world, an object is a black box that exhibits a certain behavior.
2. The behavior of this object is what which is useful for the external
world or other objects.
3. An object exposes its behavior by means of methods or functions.
4. The set of functions an object exposes to other objects or external
world acts as the interface of the object.
Does Java support Multiple inheritance?
by Chaitanya Singh
in OOPs Concept
In this post we will learn why java doesnt support multiple inheritance. We
would also see how to achieve this using interfaces in Java.
WHY JAVA DOESNT SUPPORT MULTIPLE INHERITANCE?
C++ , Common lisp and few other languages supports multiple inheritance while
java doesnt support it. It is just to remove ambiguity, because multiple
inheritance can cause ambiguity in few scenarios. One of the most common
scenario is Diamond problem.
WHAT IS DIAMOND PROBLEM?
Consider the below diagram which shows multiple inheritance as Class D extends
both Class B & C. Now lets assume we have a method definition in class A and
Class B & C overrides that method in their own way. Wait!! here the problem
comes - Because D is extending both B & C so if D wants to use the same method
which method would eligibleeither from B or C? Ambiguity. Thats the main
reason why Java doesnt support multiple inheritance.

HOW TO ACHIEVE MULTIPLE INHERITANCE IN JAVA USING INTERFACES?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface X
{
public void myMethod();
}
interface Y
{
public void myMethod();
}
class Demo
{
public void myMethod()
{
System.out.println(" Multiple inheritance example using
interfaces");
}
}
class testMultiple extends Demo implements X, Y
{
....
}
As you can see that in above example class extends only one class but it can
implements more than one interfaces. SO thats how we can achieve multiple
inheritance in Java.
Multilevel inheritance in java with example
by Chaitanya Singh
in OOPs Concept
We discussed a bit about Multilevel inheritance in types of inheritance in java. In
this tutorial we will explain multilevel inheritance with the help
of diagram and example program.
Diagram representation:

Its pretty clear with the diagram that in Multilevel inheritance there is a concept of
grand parent class. If we take the example of above diagram then class C inherits
class B and class B inherits class A which means B is a parent class of C and A is a
parent class of B. So in this case class C is implicitly inheriting the properties and
method of class A along with B thats what is called multilevel inheritance.
Example Program:
In this example we have three classes Car, Maruti and Maruti800. We have done
a setup class Maruti extends Car and class Maurit800 extends Maurti. With the
help of this Multilevel hierarchy setup our Maurti800 class is able to use the
methods of both the classes (Car and Maruti).
package beginnersbook.com;
class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{

public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph
What is an Interface in java Basics with examples
by Chaitanya Singh
in OOPs Concept
An interface in java is an abstract type which is used to specify an interface
(generic sense) that java class will implement.
DECLARATION
Interfaces are created by specifying a keyword interface. E.g.:
1
2
3
4
5
interface Interf
{
public void method1 ();
public void method2 ();
}
IMPLEMENTATION
1
2
3
4
5
6
7
8
9
10
11
12
13
//Class 1
class Bea implements Interf
{
public void method1 ()
{
System.out.println(implementation method1);
}
public void method2 ()
{
System.out.println(implementation method2);
}

public static void main(String arg[])
{
Interf i=new Interf();
14
15
16
17
18
19
i. method1 ();
}

}
KEY POINTS:
1) While providing implementation of any interface method, it needs to be
mentioned as public.
2) Class implementing any interface must implement all the methods, otherwise the
class should be declared as abstract.
3) Interface cannot be declared as private, protected or transient.
4) All the interface methods are by default abstract and public.
5) Variables declared in interface are by default public, static and final.
1
2
3
4
5
6
7
8
interface Try
{
int a=10;
public int a=10;
public static final int a=10;
final int a=10;
static int a=0;
}
All of the above statements are identical.
6) Interface variables must be initialized at the time of declaration otherwise
compiler will through an error.
1
2
3
4
interface Try
{
int x;
}
Above code will throw a compile time error.
7) Inside any implementation class, you cannot change the variables declared in
interface because by default, they are public, static and final.
1
2
3
4
5
6
7
Class Sample implement Try
{
public static void main(String arg[])
{
x=20; //compile time error
}
}
8) Any interface can extend any other interface but cannot implement it.
9) A class can implements any number of interfaces.
10) If there are having two are more same methods in two interfaces and a
class implements both interfaces, implementation of one method is enough.
1
2
3
4
interface A
{
public void aaa();
}
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface B
{
public void aaa();
}
class Central implement A,B
{
public static void main(String arg[])
{
public void aaa()
{
.....
}
}
}
11) Methods with same signature but different return type cant be implemented at
a time for two or more interfaces.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
interface A
{
public void aaa();
}
Interface B
{
public int aaa();
}

class Central implement A,B
{
public static void main(String arg[])
{
public void aaa() // error
{
}
public int aaa() // error
{
}
}
}
12) Variable names conflicts can be resolved by interface name e.g:
1
2
3
4
5
6
7
8
9
interface A
{
int x=10;
}
interface B
{
int x=100;
}
class Hello implement A,B
10
11
12
13
14
15
16
17
{
public static void Main(String arg[])
{
System.out.println(x); // reference to x is ambiguous both variables
System.out.println(A.x);
System.out.println(B.x);
}
}
BENEFITS:
Following are the benefits of interfaces:
1. Without bothering about the implementation part, we can achieve
the security of implementation
2. In java, multiple inheritances are not allowed, but alternative to that
can be provided with interfaces as a class can extend only one class but
can implement any number of interfaces. It saves you from Deadly
Diamond of Death(DDD).
How to throw exception in java with example
by Chaitanya Singh
in Exception Handling
In java we have predefined implicit exceptions such as Arithmetic Exception,
ArrayIndexOutOfBoundsException etc. There are certain conditions coded for
suchexceptions and whenever those cases or conditions occurs these exceptions are
thrown implicitly.
Do you know that a programmer can create a new exception and throw it
explicitly? In order to throw user defined exceptions throw keyword is being
used. In this tutorial, we will see how to create a new exception and throw it in
a program using throw keyword.
You can also throw an implicit exception such as Arithmetic exception using throw
in java for your defined condition.
SYNTAX OF THROW STATEMENT
throw AnyThrowableInstance;
for e.g.:
public void sample(){
//Statements
//if (somethingWrong)
IOException e = new IOException();
throw e;
//More Statements
}
Note:
A call to the above mentioned sample method should be always placed in
a try block as it is throwing a Checked Exception IOException.
Exceptions in Java are compulsorily of type Throwable. If you attempt to
throw an object that is not throwable, the compiler refuses to compile your
program and it would show a compilation error.
Flow of execution while throwing an exception using throw keyword
Whenever a throw statement is encountered in a program the next statement
doesnt execute. Control immediately transferred to try block to see if the thrown
exception is handled there. If thrown exception is handled then control
is transferred to corresponding catch block otherwise next try block is being
checked for exception and so on. If none of the try-catch block handled thrown
exception then a system generated exception message is being populated on
screen, same as we get for unhandled implicit exceptions.
EXAMPLES OF THROW EXCEPTION IN JAVA
Example 1: How to throw your own exception explicitly using throw
keyword
class MyOwnException extends Exception {
public MyOwnException(String msg){
super(msg);
}
}

public class EmployeeTest {

static void employeeAge(int age) throws MyOwnException{
if(age < 0)
throw new MyException("Age can't be less than
zero");
else
System.out.println("Input is valid!!");
}
public static void main(String[] args) {
try {
employeeAge(-2);
}
catch (MyOwnException e) {
e.printStackTrace();
}
}
}
Output:
Age cant be less than zero
Points to Note: Exception call should be in try block.
Example2: How to throw a predefined exception using throw keyword
class Exception2{
static int sum(int num1, int num2){
if (num1 == 0)
throw new ArithmeticException("First parameter is not valid");
else
System.out.println("Both parameters are correct!!");
}
public static void main(String args[]){
int ans=sum(0,12);
System.out.println("Continue Next statements");
}
}
Output:
Exception in thread main java.lang.ArithmeticException: First parameter is not valid
Similar to example 2 you can throw any predefined exception such as
NullPointerException, ArrayIndexOutOfBoundsException etc.
Target keywords: how to throw NullPointerException java, java method throws
exception, Throw exception in Java.
Java Static Class Block Methods and Variables
by Chaitanya Singh
in OOPs Concept
This tutorial is to help you understand the use of Static keyword in Java. It can
be used along with Class name, Variables, Methods and block. We will cover it one
by one in below sequence.
1. Static Class
2. Static Block
3. Static Methods
4. Static Variables
1. JAVA STATIC CLASS
A Class can be made static only if it is a nested Class. The nested static class can
be accessed without having an object of outer class.
EXAMPLES OF STATIC CLASS
Example1:
1
2
3
4
5
6
7
8
9
10
11
12
class Example1{

static class X{
static String str="Inside Class X";
}

public static void main(String args[])
{
X.str="Inside Class Example1";
System.out.println("String stored in str is- "+ X.str);
}
}
Output: String stored in str is- Inside Class Example1
Example2: Compile time Error!!
1
2
3
4
5
6
7
8
9
10
class Example2{
int num;

static class X{
static String str="Inside Class X";
num=99;
}

public static void main(String args[])
{
Example2.X obj = new Example2.X();
11
12
13
14
System.out.println("Value of num="+obj.str);
}
}
Output: Compile time error. Static inner class cannot access instance data of
outer class.
2. JAVA STATIC BLOCK
Static block is generally used to change the default values of static
variables. This block gets executed when the class is loaded in the memory.
A class can have multiple Static blocks, which will execute as per the sequence
given in the code.
EXAMPLES OF STATIC BLOCK
Example3: Single static block
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Example3{
static int num;
static String mystr;
static{
num = 97;
mystr = "Static keyword in Java";
}

public static void main(String args[])
{
System.out.println("Value of num="+num);
System.out.println("Value of mystr="+mystr);
}
}
Output:
Value of num=97
Value of mystr=Static Keyword in Java
Example4: Multiple Static blocks execution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Example4{
static int num;
static String mystr;
static{
System.out.println("Static Block 1");
num = 68;
mystr = "Block1";
}

static{
System.out.println("Static Block 2");
num = 98;
mystr = "Block2";
}

public static void main(String args[])
{
16
17
18
19
20
21
System.out.println("Value of num="+num);
System.out.println("Value of mystr="+mystr);
}
}
Output:
Static Block 1
Static Block 2
Value of num=98
Value of mystr=Block 2
3. JAVA STATIC METHODS
Static Methods can be used to access class variables without having any object of
the class. It can access non-static methods and variables with the help of
instances(objects). These methods can be accessed directly in static and non-
static methods.
Example5: Public static void main itself is a static method
1
2
3
4
5
6
7
8
9
10
11
12
class Example5{
static int i;
static String s;

public static void main(String args[]) //Its a Static Method
{
Example5 obj=new Example5();
//Non Static variables accessed using object obj
System.out.println("i:"+obj.i);
System.out.println("s:"+obj.s);
}
}
Output:
i:0
s:null
Example6: Static method display()
1
2
3
4
5
6
7
8
9
10
11
12
13
class Example6{
static int i;
static String s;

static void display()
{
//Its a Static method
Example6 obj1=new Example6();
System.out.println("i:"+obj1.i);
System.out.println("i:"+obj1.i);
}

void funcn()
{
14
15
16
17
18
19
20
21
22
23
24
//Static method called in non-static method
display();
}

public static void main(String args[]) //Its a Static Method
{
//Static method called in another static method
display();
}
}
4. JAVA STATIC VARIABLES
Static variables are also known as Class Variables.
Such variables get default values based on the data type.
Data stored in static variables is common for all the objects( or instances
) of that Class.
Memory allocation for such variables only happens once when the class is
loaded in the memory.
These variables can be accessed in any other class using class name.
Unlike non-static variables, such variables can be accessed directly in static
and non-static methods.
Example7: Static variables can be accessed without reference in Static
method
1
2
3
4
5
6
7
8
9
10
class Example7{
static int var1;
static String var2;

public static void main(String args[]) //Its a Static Method
{
System.out.println("Var1 is:"+Var1);
System.out.println("Var2 is:"+Var2);
}
}
Output:
Var1 is:0
Var2 is:null
In above example you can notice that both the variables are accessed in void main
method without any object(reference).
Example8: Static variables are common for all instances
1
2
3
4
5
class Example8{
static int Var1=77; Static integer variable
String Var2;//non-static string variable

public static void main(String args[])
{
6
7
8
9
10
11
12
13
14
15
16
17
Example8 ob1 = new Example8();
ob1.Var1=88;
ob2.Var2="I'm Object1";
Example8 ob2 = new Example8();
ob2.Var2="I'm Object2";
System.out.println("ob1 integer:"+ob1.Var1);
System.out.println("ob1 String:"+ob1.Var2);
System.out.println("ob2 integer:"+ob2.Var1);
System.out.println("ob2 STring:"+ob2.Var2);
}
}
Output:
ob1 integer:88
ob1 String:Im Object1
ob2 integer:88
ob2 String:Im Object2
In above example String variables is non-static and integer variable is Static.
So you can see that String variable value is different for both objects but integer
variable value is common for both the instances.
WHAT IS FINALLY BLOCK
1. The finally statement must be associated with a try statement and identifies a
block of statements that are executed regardless of whether or not an error
occurs within the try block.
2. After all other try-catch processing is complete, the code inside the finally block
executes. It is not mandatory to include a finally block at all, but if you do, it will
run regardless of whether an exception was thrown and handled by the try and
catch parts of the block.
3. In normal execution the finally block is executed after try block. When any
exception occurs first the catch block is executed and then finally block is executed.
4. An exception in the finally block, exactly behaves like any other exception.
5. The finally block in java code is executed even if the try or catch block
contains control transfer statements like return, break or continue.
>>To understand above concepts better refer the examples at the end of this post.
SYNTAX OF FINALLY BLOCK IN JAVA
try
{
//statements that may cause an exception
}
finally
{
//statements to be executed
}
CASES WHEREIN FINALLY BLOCK DOESNT EXECUTE
The circumstances that prevent execution of the code in a finally block are:
The death of a Thread
Using of the System. exit() method.
Due to an exception arising in the finally block.
JAVA FINALLY AND RETURN
Finally block executes even if there is a return statement in try-catch block. PFB the
example -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class JavaFinally
{
public static void main(String args[])
{
System.out.println(JavaFinally.myMethod());
}

public static int myMethod()
{
try {
return 112;
}
finally {
System.out.println("This is Finally block");
System.out.println("Finally block ran even after return statement");
}
}
}
Output of above program:
This is Finally block
Finally block ran even after return statement
112
JAVA FINALLY AND CLOSE()
Close() is generally used to close all the open streams in one go. Its a good
practice to use close() inside finally block. Since finally block executes even if
exception occurs so you can be sure that all input and output streams are closed
properly.
E.g.
1
2
3
4
5
6
7
8
9
10
11
12
....
try{
OutputStream osf = new FileOutputStream( "filename" );
OutputStream osb = new BufferedOutputStream(opf);
ObjectOutput op = new ObjectOutputStream(osb);
try{
output.writeObject(writableObject);
}
finally{
op.close();
}
}
catch(IOException e1){
System.out.println(e1);
13
14
15
16
}
...
JAVA FINALLY BLOCK WITHOUT CATCH
A try-finally block is possible without catch block. Which means a try block can be
used with finally without having a catch block.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
...
InputStream input = null;
try {
input = new FileInputStream("inputfile.txt");
} finally {
if (input != null) {
try {
in.close();
} catch (IOException exp) {
System.out.println(exp);
}
}
}
...
JAVA FINALLY AND SYSTEM.EXIT()
System.exit() statement behaves differently than return statement. Unlike
return statement whenever System.exit() gets called in try block then Finally
block doesnt get executed. Refer the below example to understand it better -
1
2
3
4
5
6
7
8
9
10
11
12
13
....
try {
//try block
System.out.println("Inside try block");
System.exit(0)
}
catch (Exception exp) {
System.out.println(exp);
}
finally {
System.out.println("Java finally block");
}
....
In the above example if the System.exit(0) gets called without any exception then
finally wont execute. However if any exception occurs while
calling System.exit(0) then finally block will be executed.
HANDLING TRY-CATCH-FINALLY BLOCK
Either a try statement should be associated with a catch block or with
finally.
Since catch performs exception handling and finally performs the cleanup,
the best approach is to merge both of them.
Syntax:
try
{
//statements that may cause an exception
}
catch ()
{
//error handling code
}
finally
{
//statements to be executed
}
EXAMPLES OF TRY CATCH FINALLY BLOCK IN JAVA
Example 1: Below example illustrates finally block when no exception
occurs in try block
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Example1{
public static void main(String args[]){

try{
System.out.println("First statement of try block");
int num=45/3;
System.out.println(num);
}

catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}

finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
finally block
Out of try-catch-finally block
Example 2: Below example illustrates finally block when exception occurs in
try block but doesnt get handled in catch block
1
2
3
4
class Example2{
public static void main(String args[]){

try{
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}

catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}

finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
finally block
System generated Arithmetic exception message
Example 3: Below example illustrates finally block in java, when exception
occurs in try block and handled in catch block
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Example3{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}

catch(ArithmeticException e){
System.out.println("ArithmeticException");
}

finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
ArithmeticException
finally block
Out of try-catch-finally block
Target keywords: exception thrown in finally block, try catch in finally
block, try/catch finally java
Thread life cycle in java and thread scheduling
by Chaitanya Singh
in Multithreading
In previous post I have covered almost all the terms related to Java threads. Here
we will learn Thread life cycle in java, well also see thread scheduling.
THREAD LIFE CYCLE IN JAVA
The start method creates the system resources necessary to run the
thread, schedules the thread to run, and calls the threads run method.
A thread becomes Not Runnable when one of these events occurs:
If sleep method is invoked.
The thread calls the wait method.
The thread is blocking on I/O.
A thread dies naturally when the run method exits.
RECOMMENDED READS:
1. Multithreading in Java
Below diagram clearly depicts the various phases of thread life cycle in java.

2. THREAD SCHEDULING
Execution of multiple threads on a single CPU, in some order, is
called scheduling.
In general, the runnable thread with the highest priority is active
(running)
Java is priority-preemptive
If a high-priority thread wakes up, and a low-priority thread is
running
Then the high-priority thread gets to run immediately
Allows on-demand processing
Efficient use of CPU
2.1 TYPES OF SCHEDULING
Waiting and Notifying
Waiting [wait()] and notifying [notify(), notifyAll()] provides means
of communication between threads that synchronize on the same object.
wait(): when wait() method is invoked on an object, the thread executing
that code gives up its lock on the object immediately and moves the thread to
the wait state.
notify(): This wakes up threads that called wait() on the same object and
moves the thread to ready state.
notifyAll(): This wakes up all the threads that called wait() on the same
object.
Running and Yielding
Yield() is used to give the other threads of the same priority a
chance to execute i.e. causes current running thread to move to runnable state.
Sleeping and Waking up
nSleep() is used to pause a thread for a specified period of time i.e.
moves the current running thread to Sleep state for a specified amount of time,
before moving it to runnable state. Thread.sleep(no. of milliseconds);
2.2 THREAD PRIORITY
When a Java thread is created, it inherits its priority from the thread that
created it.
You can modify a threads priority at any time after its creation using
thesetPriority method.
Thread priorities are integers ranging between MIN_PRIORITY (1)
andMAX_PRIORITY (10) . The higher the integer, the higher the
priority.Normally the thread priority will be 5.
2.3 ISALIVE() AND JOIN() METHODS
isAlive() method is used to determine if a thread is still alive. It is the
best way to determine if a thread has been started but has not yet completed
its run() method. final boolean isAlive();
The nonstatic join() method of class Thread lets one thread join onto the
end of another thread. This method waits until the thread on which it is called
terminates. final void join();
3. BLOCKING THREADS
When reading from a stream, if input is not available, the thread
will block
Thread is suspended (blocked) until I/O is available
Allows other threads to automatically activate
When I/O available, thread wakes back up again
Becomes runnable i.e. gets into ready state
4. GROUPING OF THREADS
Thread groups provide a mechanism for collecting multiple threads into a
single object and manipulating those threads all at once, rather than
individually.
To put a new thread in a thread group the group must
be explicitly specified when the thread is created
- public Thread(ThreadGroup group, Runnable runnable)
- public Thread(ThreadGroup group, String name)
- public Thread(ThreadGroup group, Runnable runnable, String
name)
A thread can not be moved to a new group after the thread has been
created.
When a Java application first starts up, the Java runtime system creates a
ThreadGroup named main.
Java thread groups are implemented by the java.lang.ThreadGroup class.
Target keywords: thread life cycle in java, java threading tutorial, using
threads in java, javathread run.
Types of inheritance in Java: Single,Multiple,Multilevel & Hybrid
by Chaitanya Singh
in OOPs Concept
Below are Various types of inheritance in Java. We will see each one of them one by
one with the help of examples and flow diagrams.
1) SINGLE INHERITANCE
Single inheritance is damn easy to understand. When a class extends another
one class only then we call it a single inheritance. The below flow diagram shows
that class B extends only one class which is A. Here A is a parent class of B and B
would be a child class of A.

Single Inheritance example program in Java
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}

Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
2) MULTIPLE INHERITANCE
Multiple Inheritance refers to the concept of one class extending (Or inherits)
more than one base class. The inheritance we learnt earlier had the concept of one
base class or parent. The problem with multiple inheritance is that the derived
class will have to manage the dependency on two base classes.

Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple
inheritance often leads to problems in the hierarchy. This results in unwanted
complexity when further extending the class.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support
Multiple inheritance. Multiple Inheritance is supported in C++.
3) MULTILEVEL INHERITANCE
Multilevel inheritance refers to a mechanism in OO technology where one can
inherit from a derived class, thereby making this derived class the base class for
the new class. As you can see in below flow diagram C is subclass or child class of B
and B is a child class of A. For more details and example refer Multilevel
inheritance in Java.

Multilevel Inheritance example program in Java
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
4) HIERARCHICAL INHERITANCE
In such kind of inheritance one class is inherited by many sub classes. In below
example class B,C and D inherits the same class A. A is parent class (or base
class) of B,C & D. Read More at - Hierarchical Inheritance in java with example
program.

5) HYBRID INHERITANCE
In simple terms you can say that Hybrid inheritance is a combination
of Single andMultiple inheritance. A typical flow diagram would look like below.
A hybrid inheritance can be achieved in the java in a same way as
multiple inheritance can be!! Using interfaces. yes you heard it right. By
using interfaces you can have multiple as well as hybrid inheritance in Java.
Read the full article here - hybrid inheritance in java with example program.

----------------------------------------------------------------------------------------
JUnit 4 Tutorial 1 Basic Usage
Import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
public class JunitTest1 {
private Collection collection;
@BeforeClass
public static void oneTimeSetUp() {
// one-time initialization code
System.out.println("@BeforeClass - oneTimeSetUp");
}
@AfterClass
public static void oneTimeTearDown() {
// one-time cleanup code
System.out.println("@AfterClass - oneTimeTearDown");
}
@Before
public void setUp() {
collection = new ArrayList();
System.out.println("@Before - setUp");
}
@After
public void tearDown() {
collection.clear();
System.out.println("@After - tearDown");
}
@Test
public void testEmptyCollection() {
assertTrue(collection.isEmpty());
System.out.println("@Test - testEmptyCollection");
}
@Test
public void testOneItemCollection() {
collection.add("itemA");
assertEquals(1, collection.size());
System.out.println("@Test - testOneItemCollection");
}
}
Result :

@BeforeClass - oneTimeSetUp
@Before - setUp
@Test - testEmptyCollection
@After - tearDown
@Before - setUp
@Test - testOneItemCollection
@After - tearDown
@AfterClass - oneTimeTearDown

In JUnit 4, you have to declare @BeforeClass and @AfterClass method as static
method.
JUnit 4 Tutorial 2 Expected Exception Test




import org.junit.*;

public class JunitTest2 {

@Test(expected = ArithmeticException.class)
public void divisionWithException() {
int i = 1/0;
}

}

In above example, the divisionWithException() method will throw
an ArithmeticException Exception, since this is an expected exception, so the unit test
will pass.


JUnit 4 Tutorial 3 Ignore Test




import org.junit.*;
public class JunitTest3 {
@Ignore("Not Ready to Run")
@Test
public void divisionWithException() {
System.out.println("Method is not ready yet");
}
}
In above example, JUnit will not test the divisionWithException() method.



JUnit 4 Tutorial 4 Time Test


import org.junit.*;
/**
* JUnit TimeOut Test
* @author mkyong
*
*/
public class JunitTest4 {
@Test(timeout = 1000)
public void infinity() {
while (true);
}
}

In above example, the infinity() method will not return, so the JUnit engine will mark it
as failed and throw an exception


JUnit 4 Tutorial 5 Suite Test


The Suite Test means bundle a few unit test cases and run it together. In Junit,
both @RunWith and @Suite annotation are used to run the suite test.

The below example means both unit test JunitTest1 and JunitTest2 will run together
after JunitTest5 is executed.


import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
JunitTest1.class,
JunitTest2.class
})
public class JunitTest5 {
}
Result :

@BeforeClass - oneTimeSetUp
@Before - setUp
@Test - testEmptyCollection
@After - tearDown
@Before - setUp
@Test - testOneItemCollection
@After - tearDown
@AfterClass - oneTimeTearDown


JUnit 4 Tutorial 6 Parameterized Test




The Parameterized Test means vary parameter value for unit test. In JUnit,
both @RunWith and @Parameter annotation are use to provide parameter value for
unit test, @Parameters have to return List[], and the parameter will pass into class
constructor as argument.




import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(value = Parameterized.class)
public class JunitTest6 {
private int number;
public JunitTest6(int number) {
this.number = number;
}
@Parameters
public static Collection<Object[]> data() {
Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4}
};
return Arrays.asList(data);
}

@Test
public void pushTest() {
System.out.println("Parameterized Number is : " + number);
}
}

Result :
Parameterized Number is : 1
Parameterized Number is : 2
Parameterized Number is : 3
Parameterized Number is : 4


List of Scenarios


1. Create a ArrayList ->Add Element -> Read Element
2. Create HashMap -> Add Element -> Read Element Tip: HashMap has Key/Value
pairs
3. Read and Write from Text File.
Tip : You will be using these Classes for doing the same: File, FileWriter,
BufferedWriter, FileReader, BufferedReader
4. JUNIT : Create simple test case ( may be launching google.com only) through JUNIT
@Test annotation

Tip : You need to download JUNIT jar or configure in Eclipse. Public static
main should not used for testfile class

5. Firefox Profile : Create Firefox profile manually and write Java Program to use that
profile instead of default webdriver profile
6. Handling Javascript enabled message : Create Java Program to handle message
popping up for enabling javascript. Tip : You have use DesiredCapabilities Class to do
the same
7. Identifying WebElement on Webpage : Use Class,id,name or any other attribute
available to identify same element. You may use Absolute or Relative path. You may
use gmail.com username website.
8. Extracting Links : Extract all links (name and url ) from bbc.com Tip : You will have to
use findelements and tagname
9. Check Links : Click all links on bbc.com and make sure they working. Tip : Check
title after every click of like and make sure it does not contain 500 error.
10.Dropdown : Visit Timesofindia.com and change City drop down . Tip : Use Select
class
11.RadioButton : Visit below URL and select checkboxes. Make sure you use
findelements to get group of radioButton and then select rather than selecting
individually.
http://www.echoecho.com/htmlforms10.htm
12. Screenshot : Write program to take screenshot of the page in test case.
13.Implicitwait : Use implicit wait in testcase . Tip : Visit gmail.com -> Change definition
of object to wrong value and make sure NoSuchElement exeption is thrown after 30
seconds.
14.New Tab/New Window/Pop Ups : Visit hdfcbank.com and click Credit Card/Personal
Account on write side. Do something on new window opened on click Credit
Cards/Personal Account.
15. Certificate Error : Create Program to handle Certificate Error/acceptance page. Tip :
Google and find out the code. The code should run.
16 . WebTable/Frames : Visit espncricinfo.com and visit any fill scoreboard for a match
and try to create a test case which adds individual batsman score and then compare
this total to total displayed on the scoreboard.
17.Javascript Error : Visit rediif.com -> Click Signin -> Click Ok without giving
username/password - > Accept the error alert.

JUNIT 4 VS TESTNG
JUnit 4 and TestNG are both very popular unit test framework in Java. Both frameworks
look very similar in functionality. Which one is better? Which unit test framework should i
use in Java project?
Here i did a feature comparison between JUnit 4 and TestNG.



1. Annotation Support
The annotation supports are implemented in both JUnit 4 and TestNG look similar.
Feature JUnit 4 TestNG
test annotation @Test @Test
run before all tests in
this suite have run
@BeforeSuite
run after all tests in
this suite have run
@AfterSuite
run before the test @BeforeTest
run after the test @AfterTest
run before the first
test method that
belongs to any of
these groups is
invoked
@BeforeGroups
run after the last test
method that belongs
to any of these groups
is invoked
@AfterGroups
run before the first
test method in the
current class is
invoked
@BeforeClass @BeforeClass
run after all the test
methods in the
current class have
been run
@AfterClass @AfterClass
run before each test
method
@Before @BeforeMethod
run after each test
method
@After @AfterMethod
ignore test @ignore @Test(enbale=false)
expected exception
@Test(expected =
ArithmeticException.class)
@Test(expectedExceptions =
ArithmeticException.class)
timeout @Test(timeout = 1000) @Test(timeout = 1000)

The main annotation differences between JUnit4 and TestNG are
1. In JUnit 4, we have to declare @BeforeClass and @AfterClass method as static
method. TestNG is more flexible in method declaration, it does not have this constraints.
2. 3 additional setUp/tearDown level: suite and group (@Before/AfterSuite,
@Before/AfterTest, @Before/AfterGroup). See more detail here.
J Unit 4
@BeforeClass
public static void oneTimeSetUp() {
// one-time initialization code
System.out.println("@BeforeClass - oneTimeSetUp");
}
TestNG
@BeforeClass
public void oneTimeSetUp() {
// one-time initialization code
System.out.println("@BeforeClass - oneTimeSetUp");
}
In JUnit 4, the annotation naming convention is a bit confusing, e.g Before, After and
Expected, we do not really understand what is Before and After do, and what we
Expected from test method? TestNG is easier to understand, it using BeforeMethod,
AfterMethod and ExpectedException instead.


3

DataProvider - From Excel

Scenario : Consider a Test Case which requires you to login into a website like
gmail.com , with different User Id and Passwords. User Id and Passwords are stored in
Excel in below format. Sheet has third column for Run Mode also.

Solution : We will use @DataProvider annotation available in TestNG to handle above
scenario.
How : @DataProvider annotation method will access data from excel and pass the
same in the form of HashTable/Data Object to the test method.

testdata.xlsx ( It has sheet with name "TestData")

Username | Password | RunMode
hsingh | password1 | Y
psingh | password2 | Y
msingh | password3 |Y


==================================================================
=======

package rough;
import java.util.Hashtable;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.qtpselenium.hybrid.util.Xls_Reader;

public class xldataprovider {

@Test(dataProvider="xldata")
public void tescase(Hashtable<String,String> data){

System.out.println(data.get("Username"));
System.out.println(data.get("Password"));

}

@DataProvider
public Object[][] xldata(){

Object[][] data=null;
Xls_Reader xls= new
Xls_Reader("C://Users//har//Documents//Eclipseworkspace//hybridframework//src//roug
h//testdata.xlsx");

Hashtable<String,String> table =null;
//Find number of columns in xls

int numofcols=0;
while(!xls.getCellData("TestData", numofcols, 1).equals("")){

numofcols++;

}

System.out.println("Number of Columns are : " + numofcols) ;

//Find number of rows in xls

int numofrows=0;
while(!xls.getCellData("TestData", 0, numofrows+2).equals("")){ //numofrow+2 is
given as we need to start from 2nd row.First row is column Heading

// System.out.println(xls.getCellData("TestData", 0, numofrows));
numofrows++;

}


System.out.println("Number of rows are : " + numofrows) ;

// initialising data object with number of rows and one column.The data of one row will
be put in one column of Hashtable

data= new Object[numofrows][1]; //The column will be 1 only as we will put data in
hash table.

// Putting data in data Object

for(int row=2;row<numofrows+2;row++ ){
table=new Hashtable<String,String>();
for(int col=0;col<numofcols;col++){

table.put(xls.getCellData("TestData", col, 1),xls.getCellData("TestData", col,
row) );

}

data[row-2][0]= table;

}


return data;
}

}

------------------------------------------------------------------------------------------
testdata.xlsx ( It has sheet with name "TestData")

Username | Password | RunMode
hsingh | password1| Y
psingh | password2 | Y
msingh | password3| Y

dataprovider ( will always be 1 column)



















Xls_Reader Class

package com.qtpselenium.hybrid.util;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFHyperlink;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class Xls_Reader {
public static String filename =
System.getProperty("user.dir")+"\\src\\config\\testcases\\TestData.xlsx";
public String path;
public FileInputStream fis = null;
public FileOutputStream fileOut =null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row =null;
private XSSFCell cell = null;

public Xls_Reader(String path) {

this.path=path;
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
// returns the row count in a sheet
public int getRowCount(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return 0;
else{
sheet = workbook.getSheetAt(index);
int number=sheet.getLastRowNum()+1;
return number;
}

}

// returns the data from a cell
public String getCellData(String sheetName,String colName,int rowNum){
try{
if(rowNum <=0)
return "";

int index = workbook.getSheetIndex(sheetName);
int col_Num=-1;
if(index==-1)
return "";

sheet = workbook.getSheetAt(index);
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
col_Num=i;
}
if(col_Num==-1)
return "";

sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum-1);
if(row==null)
return "";
cell = row.getCell(col_Num);

if(cell==null)
return "";
//System.out.println(cell.getCellType());
if(cell.getCellType()==Cell.CELL_TYPE_STRING)
return cell.getStringCellValue();
else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC ||
cell.getCellType()==Cell.CELL_TYPE_FORMULA ){

String cellText = String.valueOf(cell.getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// format in form of M/D/YY
double d = cell.getNumericCellValue();

Calendar cal =Calendar.getInstance();
cal.setTime(HSSFDateUtil.getJavaDate(d));
cellText =
(String.valueOf(cal.get(Calendar.YEAR))).substring(2);
cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" +
cal.get(Calendar.MONTH)+1 + "/" +
cellText;

//System.out.println(cellText);

}



return cellText;
}else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());

}
catch(Exception e){

e.printStackTrace();
return "row "+rowNum+" or column "+colName +" does not exist in xls";
}
}

// returns the data from a cell
public String getCellData(String sheetName,int colNum,int rowNum){
try{
if(rowNum <=0)
return "";

int index = workbook.getSheetIndex(sheetName);

if(index==-1)
return "";


sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum-1);
if(row==null)
return "";
cell = row.getCell(colNum);
if(cell==null)
return "";

if(cell.getCellType()==Cell.CELL_TYPE_STRING)
return cell.getStringCellValue();
else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC ||
cell.getCellType()==Cell.CELL_TYPE_FORMULA ){

String cellText = String.valueOf(cell.getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// format in form of M/D/YY
double d = cell.getNumericCellValue();

Calendar cal =Calendar.getInstance();
cal.setTime(HSSFDateUtil.getJavaDate(d));
cellText =
(String.valueOf(cal.get(Calendar.YEAR))).substring(2);
cellText = cal.get(Calendar.MONTH)+1 + "/" +
cal.get(Calendar.DAY_OF_MONTH) + "/" +
cellText;

// System.out.println(cellText);

}



return cellText;
}else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
}
catch(Exception e){

e.printStackTrace();
return "row "+rowNum+" or column "+colNum +" does not exist in xls";
}
}

// returns true if data is set successfully else false
public boolean setCellData(String sheetName,String colName,int rowNum, String
data){
try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);

if(rowNum<=0)
return false;

int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;


sheet = workbook.getSheetAt(index);


row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equals(colName))
colNum=i;
}
if(colNum==-1)
return false;

sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum-1);
if (row == null)
row = sheet.createRow(rowNum-1);

cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);

// cell style
//CellStyle cs = workbook.createCellStyle();
//cs.setWrapText(true);
//cell.setCellStyle(cs);
cell.setCellValue(data);

fileOut = new FileOutputStream(path);

workbook.write(fileOut);

fileOut.close();

}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}


// returns true if data is set successfully else false
public boolean setCellData(String sheetName,String colName,int rowNum, String
data,String url){
//System.out.println("setCellData setCellData******************");
try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);

if(rowNum<=0)
return false;

int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;


sheet = workbook.getSheetAt(index);
//System.out.println("A");
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equalsIgnoreCase(colName))
colNum=i;
}

if(colNum==-1)
return false;
sheet.autoSizeColumn(colNum); //ashish
row = sheet.getRow(rowNum-1);
if (row == null)
row = sheet.createRow(rowNum-1);

cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);

cell.setCellValue(data);
XSSFCreationHelper createHelper = workbook.getCreationHelper();

//cell style for hyperlinks
//by default hypelrinks are blue and underlined
CellStyle hlink_style = workbook.createCellStyle();
XSSFFont hlink_font = workbook.createFont();
hlink_font.setUnderline(XSSFFont.U_SINGLE);
hlink_font.setColor(IndexedColors.BLUE.getIndex());
hlink_style.setFont(hlink_font);
//hlink_style.setWrapText(true);

XSSFHyperlink link = createHelper.createHyperlink(XSSFHyperlink.LINK_FILE);
link.setAddress(url);
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);

fileOut = new FileOutputStream(path);
workbook.write(fileOut);

fileOut.close();

}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}



// returns true if sheet is created successfully else false
public boolean addSheet(String sheetname){

FileOutputStream fileOut;
try {
workbook.createSheet(sheetname);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

// returns true if sheet is removed successfully else false if sheet does not exist
public boolean removeSheet(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return false;

FileOutputStream fileOut;
try {
workbook.removeSheetAt(index);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if column is created successfully
public boolean addColumn(String sheetName,String colName){
//System.out.println("**************addColumn*********************");

try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return false;

XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

sheet=workbook.getSheetAt(index);

row = sheet.getRow(0);
if (row == null)
row = sheet.createRow(0);

//cell = row.getCell();
//if (cell == null)
//System.out.println(row.getLastCellNum());
if(row.getLastCellNum() == -1)
cell = row.createCell(0);
else
cell = row.createCell(row.getLastCellNum());

cell.setCellValue(colName);
cell.setCellStyle(style);

fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();

}catch(Exception e){
e.printStackTrace();
return false;
}

return true;


}
// removes a column and all the contents
public boolean removeColumn(String sheetName, int colNum) {
try{
if(!isSheetExist(sheetName))
return false;
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet=workbook.getSheet(sheetName);
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
style.setFillPattern(HSSFCellStyle.NO_FILL);



for(int i =0;i<getRowCount(sheetName);i++){
row=sheet.getRow(i);
if(row!=null){
cell=row.getCell(colNum);
if(cell!=null){
cell.setCellStyle(style);
row.removeCell(cell);
}
}
}
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;

}
// find whether sheets exists
public boolean isSheetExist(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1){
index=workbook.getSheetIndex(sheetName.toUpperCase());
if(index==-1)
return false;
else
return true;
}
else
return true;
}

// returns number of columns in a sheet
public int getColumnCount(String sheetName){
// check if sheet exists
if(!isSheetExist(sheetName))
return -1;

sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);

if(row==null)
return -1;

return row.getLastCellNum();



}
//String sheetName, String testCaseName,String keyword ,String URL,String
message
public boolean addHyperLink(String sheetName,String screenShotColName,String
testCaseName,int index,String url,String message){
//System.out.println("ADDING addHyperLink******************");

url=url.replace('\\', '/');
if(!isSheetExist(sheetName))
return false;

sheet = workbook.getSheet(sheetName);

for(int i=2;i<=getRowCount(sheetName);i++){
if(getCellData(sheetName, 0, i).equalsIgnoreCase(testCaseName)){
//System.out.println("**caught "+(i+index));
setCellData(sheetName, screenShotColName, i+index, message,url);
break;
}
}


return true;
}
public int getCellRowNum(String sheetName,String colName,String cellValue){

for(int i=2;i<=getRowCount(sheetName);i++){
if(getCellData(sheetName,colName , i).equalsIgnoreCase(cellValue)){
return i;
}
}
return -1;

}

// to run this on stand alone
public static void main(String arg[]) throws IOException{

//System.out.println(filename);
Xls_Reader datatable = null;


datatable = new
Xls_Reader("H:\\Student_Selenium_Workspaces\\Framework_Weekend\\src\\Framewor
k_XL_Files\\Controller.xlsx");
for(int col=0 ;col< datatable.getColumnCount("TC5"); col++){
System.out.println(datatable.getCellData("TC5", col, 1));
}
}


}




Data Provider Use(Non XL use) - TestNG
package test;

import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;



public class dataprovider {


@Test(dataProvider="testdata")
public void testRegister(String username,String password){

System.out.println(username + password);


}


@DataProvider
public Object[][] testdata(){

//number of rows reperesents number of times test has to be repeated
//number of rows is in our case is 2 , so test will be repeated 2 times
//number of columns is number of parameter in data. We have 2 as username and
password
Object[][] data = new Object[2][2];

//first row
data[0][0]= "hm_singh2002@yahoo.com";
data[0][1]="password1";


//second row
data[1][0]= "hmsingh@gmail.com";
data[1][1]="password1";



return data;


}

}



Usage of Log4j in Selenium

Scenario : During the running of test case user wants some information to be logged in
the console. Information could be any detail about present activity being performed by
the test case step.

Solution : log4j jar api helps you to get the above scenario implemented in the running
of Test Case.

How : Follow below steps :

1) Include log4j jar in build path

2) Create log4j.properties in the package with below details


#Application Logs
log4j.logger.devpinoyLogger=DEBUG, dest1
log4j.appender.dest1=org.apache.log4j.RollingFileAppender
log4j.appender.dest1.maxFileSize=5000KB
log4j.appender.dest1.maxBackupIndex=3
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n
log4j.appender.dest1.File=C:\\testing\\Application.log
#do not append the old file. Create a new log file everytime
log4j.appender.dest1.Append=false

3) Now do logging from any test case by using code like below

import org.apache.log4j.Logger;
public class Logging_Example {
/**
* @param args
*/
public static void main(String[] args) {

// add log4j.jar
// add log4j.propertie directly inside the src folder
// create the object in the code

Logger APPLICATION_LOGS = Logger.getLogger("devpinoyLogger");
APPLICATION_LOGS.debug("hello");
APPLICATION_LOGS.debug("We are wrinting in to a log file");
APPLICATION_LOGS.debug("starting the test case xyz test");

}
}
Automation Lifecycle
1) Automation Feasibility Study


AUT automation fasibilty
Test Case automation feasibilty
Tool feasibility
2) Test Strategy


Design about Automation Framework
Schedule, Number of resources,Defining SLA,Defining In-Scope/Out-Scope, Return on
Investment
3) Environment Setup


Should be setup in Regression enviornment,
Licenses
Comparison Tool, Text Editor, Supporting Tool
AUT access and valid credentials
Implementation of automation framework
4) Test Script Development

5) Test Script Execution

6) Test Result Generation and Analysis



Reflection API


Scenario : In Keyword Driven Framework we have Test Case in below format. We need
to implement framework in such a way that underlying framework code works
like ReflectionAPITestCase.java





==================================================================
===
package test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionAPITestCase {
public static void main(String[] args) {
actions.CallMethod("OpenBrowser","","http://www.google.com");
actions.CallMethod("EnterText", "//input[@id='gs_htif0']", "Selenium");
actions.CallMethod("ClickButton", "//button[@id='gbqfba']", "");
}

}

==================================================================
==


Solution : Reflection API can be helpful to implement above. It will help you to call
methods of a class as shown below

package test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class actions {

public static void CallMethod(String Action,String Object,String Value) {

Method method= actions.class.getMethod(Action, String.class,String.class);
method.invoke(Action,Object,Value);

}

public static void OpenBrowser(String Object,String Value){
System.out.println("Opening browser URL:" + Value );
}

public static void EnterText(String Object,String Value){
System.out.println("Entering text in : " + Object + " Value:" + Value) ;
}


public static void ClickButton(String Object,String Value){
System.out.println("Clicking Object : " + Object ) ;

}


}



Listener,Mousehover,Right Click, Co-ordinates
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;


public class ListenerTest {

/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
WebDriver web_driver = new FirefoxDriver();
EventFiringWebDriver driver = new EventFiringWebDriver(web_driver);
MyListener myListener = new MyListener();
driver.register(myListener);

driver.navigate().to("http://www.gmail.com");
driver.findElement(By.xpath("html/body/table[2]/tbody/tr/td[1]/font/table/tbody/tr[3]/t
d[2]/font/a")).click();
Thread.sleep(5000L);
// back button
System.out.println("Going to click back button");
driver.navigate().back();
System.out.println("Clicking back button");
Thread.sleep(5000L);
driver.navigate().forward();
Thread.sleep(5000L);

driver.quit();
}

}

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.internal.Coordinates;
import org.openqa.selenium.internal.Locatable;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.openqa.selenium.support.events.internal.EventFiringMouse;


public class MouseMovement {


public static void main(String[] args) {


WebDriver web_driver = new FirefoxDriver();
EventFiringWebDriver driver = new EventFiringWebDriver(web_driver);
MyListener myListener = new MyListener();
driver.register(myListener);

driver.get("http://timesofindia.com");
EventFiringMouse mouse = new EventFiringMouse(driver , myListener);
// move mouse
Locatable hoverItem = (Locatable)
driver.findElement(By.xpath("html/body/div[3]/table[3]/tbody/tr[1]/td[1]/div[12]/div[2]/div[2
]/ul/li/a"));
Coordinates c= hoverItem.getCoordinates();
try{
mouse.mouseMove(c);
}catch(Exception e1){


}
// right click
driver.findElement(By.xpath("html/body/div[3]/table[3]/tbody/tr[1]/td[1]/div[12]/div[2]/
div[2]/ul/li/a")).sendKeys(Keys.chord(Keys.SHIFT,Keys.F10));
// coordinates
Point
p=driver.findElement(By.xpath("html/body/div[3]/table[3]/tbody/tr[1]/td[1]/div[12]/div[2]/di
v[2]/ul/li/a")).getLocation();
System.out.println(p.x);
System.out.println(p.y);




}

}

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.events.AbstractWebDriverEventListener;


public class MyListener extends AbstractWebDriverEventListener{


public void afterNavigateBack(WebDriver driver) {
System.out.println("Hello");
}

}


Firefox Profile Handling - 2
package test;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;

public class firefoxprofile {

public static void main(String[] args){

//Below link contains 3 files which if clicked will open Window native window for
saving file or open it .
// We want to avoid above situation so firefox profile needs to set in such a way
that it does not ask anything and download to pre-selected directory.
// All above needs profile to be set.
// If you put "about:config" in browser window , you will see all preferences which
can be set.

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/msword,application/x-rar-compressed,application/octet-
stream,application/csv,text/csv");

WebDriver driver = new FirefoxDriver(profile);
driver.get("http://qtpselenium.com/test/testdownload.php");
driver.findElement(By.xpath("html/body/a[1]")).click();
driver.findElement(By.xpath("html/body/a[2]")).click();
driver.findElement(By.xpath("html/body/a[3]")).click();




}


}


Handling Cookies
package test;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class managingcookies {
public static void main(String[] args){

WebDriver driver= new FirefoxDriver();
driver.get("https://gmail.com");
Set<Cookie> cookee= driver.manage().getCookies();
Iterator<Cookie> it = cookee.iterator() ;
while(it.hasNext())
{
Cookie c= it.next();
System.out.println(c.getDomain() + c.getName() );

}

driver.manage().deleteAllCookies() ;

}


}



Calender - Selecting Dates

Below code will help you pass dates to method and select the dates on the
calender



package test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class calenderhandling {



public static void main(String[] args)
{
WebDriver driver = new FirefoxDriver();
driver.get("http://spicejet.com/");
driver.findElement(By.xpath("//input[@name='departDate1text']")).click();

selectdate("20",driver);
driver.findElement(By.xpath(".//*[@id='departDate2text']")).click();

selectdate("22",driver);
}


public static void selectdate(String date1, WebDriver driver){
String xpath ;
for(int i = 1;i<=5;i++){
for(int j = 1;j<=7;j++)
{
xpath=".//*[@id='ui-datepicker-div']/table/tbody/tr[" + String.valueOf(i) + "]/td[" +
String.valueOf(j) + "]";
System.out.println(driver.findElement(By.xpath(xpath)).getText());
if(driver.findElement(By.xpath(xpath)).getText().equals(date1))
{
driver.findElement(By.xpath(xpath)).click() ;
return ;
}
}
}


}





}



PageLoad Timeout


//Wait for page to load for specified time and if page is not loaded it will throw an
exception.


driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);


Simulating the Keyboard Keypress Event
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.firefox.FirefoxDriver;


public class keyboardpress {

public static void main(String[] args){


WebDriver driver = new FirefoxDriver();
driver.get("http://www.rediff.com/");
driver.findElement(By.xpath("//a[@title='Already a user? Sign in']")).click();
driver.findElement(By.xpath("//input[@id='c_uname']")).sendKeys(Keys.ENTER);



}


}



Handling Tabbed Window and Pop-Ups

Logic : Tabbed window in Webdriver is new window/popup only , so they have same
logic for handling.

Step 1 : When you expect mutiple windows have opened ,
use driver.getWindowHanldes() to get the Handle of all windows.
Step 2 : Pass above object conatining mutiple window to Set object like below
Set<String> win = driver.getWindowHandles();

Step 3 : Pass above Set object to Iterator object

Iterator<String> it = win.iterator ;

Step 4 : Now use next() method of iterator to traverse the iterator and get Window
Handle String of desired window.

Step 5 : Once desired Window Handle String is obtained , use below switchTo() method
to shift focus.

driver.switchTo().window(winpopup) ;


Code Snippet

package test;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Tabbedbrowsingandwinpopup {

public static void main(String[] args) {


WebDriver driver = new FirefoxDriver();
driver.get("http://www.hdfc.com/") ;
driver.findElement(By.xpath(".//*[@id='acc-1-head-2']/a")).click();
driver.findElement(By.xpath(".//*[@id='acc-1-section-2']/li[2]/a")).click(); //Trying to
click Call us under Customer Care

// Above click opens new tab so multiple windows are now open. In Webdriver new
tabs are opened in new window.

Set<String> win = driver.getWindowHandles();

// Window handles are passed to iterator

Iterator<String> it= win.iterator() ;

// By Default iterator position is before the first element. So first next() will place the
iterator at first window handle string

System.out.println(it.next());

// Below next() will place iterator to second window handle string(our desired window)

String winpopup= it.next();

//Use switch to for shifting focus to that new tab/window .

driver.switchTo().window(winpopup) ;

//clicking below on element of new tab

driver.findElement(By.xpath("html/body/table/tbody/tr[2]/td/table/tbody/tr/td[3]/table/tb
ody/tr/td/table/tbody/tr[1]/td/table/tbody/tr[2]/td/p[2]/a")).click();

// Above click click on tabbed window has opened popup

win = driver.getWindowHandles();
it= win.iterator() ;

// Below next() place focus on first window handle string

System.out.println(it.next());

// Below next() place focus on tabbed window handle string

System.out.println(it.next());

// Below next() will give widow string we are desiring

winpopup= it.next();
driver.switchTo().window(winpopup) ;
driver.findElement(By.xpath(".//*[@id='popup']/table/tbody/tr/td/table[2]/tbody/tr/td/tabl
e[1]/tbody/tr[4]/td/p/font/b/a")).click();

}


}


Finding Links on Header/Footer and Check for Broken Links

Links on Header/Footer

1) Logic is to find the Header/Footer element by FindElement and then use
FindElements to get all <a> tag elements for it. <a> tags are links.


WebElement footer= driver.findElement(By.xpath("//div[@id='footer']"));
int i = footer.findElements(By.tagName("a")).size();
List<WebElement> footlinks = footer.findElements(By.tagName("a"));


2) Find all broken links : Once you get all link webelement of Footer/Header, click on
each of them and check browser title. If browser title has "404" then , the link is broken.
You also need to use driver.navigate() here as you have to go forth and back on the
page.

Note (very important) : Make sure you populate "footer" again for each time you come
back on main page , as DOM will be changed and simpley traversing the footlinks may
not work.

Code Snippet

package test;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class brokenheaderfooter {
public static void main(String[] args) throws InterruptedException{

WebDriver driver = new FirefoxDriver();
driver.navigate().to("http://www.google.com/"); // Use navigate instead of driver.get()

WebElement footer= driver.findElement(By.xpath("//div[@id='footer']")); // Get Footer
element which contains all footer links
System.out.println(footer.findElements(By.tagName("a")).size()) ;
List<WebElement> footlinks = footer.findElements(By.tagName("a"));
int i = footer.findElements(By.tagName("a")).size(); //Get number of links

for(int j = 0;j<i;j++){ //create loop based upon number of links to traverse all links
footer= driver.findElement(By.xpath("//div[@id='footer']")); // We are re-creating
"footer" webelement as DOM changes after navigate.back()
footer.findElements(By.tagName("a")).get(j).getText();
footer.findElements(By.tagName("a")).get(j).click();
Thread.sleep(3000);
System.out.println(driver.getTitle());
if(driver.getTitle().contains("404")) {
System.out.println("404 Found");
}
driver.navigate().back();
Thread.sleep(4000);
}
}
} Links on Header/Footer

1) Logic is to find the Header/Footer element by FindElement and then use
FindElements to get all <a> tag elements for it. <a> tags are links.


WebElement footer= driver.findElement(By.xpath("//div[@id='footer']"));
int i = footer.findElements(By.tagName("a")).size();
List<WebElement> footlinks = footer.findElements(By.tagName("a"));


2) Find all broken links : Once you get all link webelement of Footer/Header, click on
each of them and check browser title. If browser title has "404" then , the link is broken.
You also need to use driver.navigate() here as you have to go forth and back on the
page.

Note (very important) : Make sure you populate "footer" again for each time you come
back on main page , as DOM will be changed and simpley traversing the footlinks may
not work.

Code Snippet

package test;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class brokenheaderfooter {
public static void main(String[] args) throws InterruptedException{

WebDriver driver = new FirefoxDriver();
driver.navigate().to("http://www.google.com/"); // Use navigate instead of driver.get()

WebElement footer= driver.findElement(By.xpath("//div[@id='footer']")); // Get Footer
element which contains all footer links
System.out.println(footer.findElements(By.tagName("a")).size()) ;
List<WebElement> footlinks = footer.findElements(By.tagName("a"));
int i = footer.findElements(By.tagName("a")).size(); //Get number of links

for(int j = 0;j<i;j++){ //create loop based upon number of links to traverse all links
footer= driver.findElement(By.xpath("//div[@id='footer']")); // We are re-creating
"footer" webelement as DOM changes after navigate.back()
footer.findElements(By.tagName("a")).get(j).getText();
footer.findElements(By.tagName("a")).get(j).click();
Thread.sleep(3000);
System.out.println(driver.getTitle());
if(driver.getTitle().contains("404")) {
System.out.println("404 Found");
}
driver.navigate().back();
Thread.sleep(4000);
}
}
}

Changing firefox Profile - WebDriver

There are situation where you need to change firefoxprofile at run time.

Example are as followed :

1) Accepting untrusted certificates

FirefoxProfile profile= new FirefoxProfile();
profile.setAssumeUntrustedCertificateIssuer(false);
WebDriver driver = new FirefoxDriver(profile);

2) Adding user extension ( like firebug ) at run time

Download the firebug xpi file from mozilla and start the profile as follows:
File file = new File("firebug-1.8.1.xpi");
FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(file);
profile.setPreference("extensions.firebug.currentVersion", "1.8.1"); // Avoid startup
screen
WebDriver driver = new FirefoxDriver(firefoxProfile);


You can also use profile manager manually and assign it to webdriver. Use below
code after creating your profilethrough profile manager

One way is:

System.setProperty(webdriver.firefox.profile, profileName);
WebDriver webDriver = new FirefoxDriver();

Another way is:

ProfilesIni profilesIni = new ProfilesIni();
// Clone the named profile
FirefoxProfile profile = profilesIni.getProfile(profileName);
WebDriver webDriver = new FirefoxDriver(profile);
Important Methods of Webdriver Class


driver.get(https://www.google.com/) //Load new webpage in current window.

driver.navigate().to("https://www.google.com/") //Also loads webpage in current window
, but forward and back button can be used.
e.g driver.navigate().back();

driver.getCurrentUrl()

driver.getPageSource()

driver.getTitle()

driver.getWindowHandle() //Return an opaque handle to this window that uniquely
identifies it within this driver instance. This can be used to switch to this window at a
later date

driver.getWindowHandles() //Return a set of window handles which can be used to
iterate over all open windows of this webdriver instance by passing them to
#switchTo().window(String)

driver.close() //Close the current window, quitting the browser if it's the last window
currently open.

driver.quit() //Quits this driver, closing every associated window.


There is nothing special about how to get the value of Ajax Droplist. The below code is
self-explanatory.

Few points in below code :
1) The suggestion are in Table.
2) The number of suggestion is unknown at compile time, so we have to use increasing
variable for creating xpath of suggestion element
3) Since loop to get all element will run indefinately so NoSuchElement exception needs
to be handled.


package test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class googleajaxlist {
public static void main(String[] args) throws InterruptedException{

WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
driver.findElement(By.xpath("//input[@class='gbqfif']")).sendKeys("harp");
Thread.sleep(4000); //This sleep is to make sure suggestion got is for word we want.
int i = 1;
String xp;

try {

while(true){
System.out.println(String.valueOf(i)); // Needs to convert integer variable to String
xp= "//*[@id='gsr']/table/tbody/tr/td[2]/table/tbody/tr[" + String.valueOf(i) +
"]/td/div/table/tbody/tr/td[1]"; //variable xpath string
System.out.println(xp);
System.out.println(driver.findElement(By.xpath(xp)).getText()) ; // getText() is used to
get the suggestion text
i++;

}

} catch ( NoSuchElementException e ) {}; //Exception handling is done for non-existing
element at end of the loop


}

}


Migrating from Selenium RC to WebDriver

Step 1: The first step when starting the migration is to change how you obtain your
instance of Selenium. When using Selenium RC, this is done like so:

Selenium selenium = new DefaultSelenium("localhost", 4444,
"*firefox","http://www.yoursite.com");
selenium.start();


This should be replaced like so:

WebDriver driver = new FirefoxDriver();
Selenium selenium = new WebDriverBackedSelenium(driver,
"http://www.yoursite.com");

Step 2 : Once your tests execute without errors, the next stage is to migrate the actual
test code to use the WebDriver APIs. Depending on how well abstracted your code is,
this might be a short process or a long one. In either case, the approach is the same
and can be summed up simply: modify code to use the new API when you come to edit
it.
Database Connectivity - WebDriver
Assumption : We have MySQL database as backend.


Step 1 : Download MySQL

Step 2: Navigate to bin directory of SQL server and create some table and insert data
as shown below










Step 3 : Now in Eclipse you need jar for database connectivity . The jar contains jar for
drivers. MySql database has different jar and Oracle would have different.

Download jar for Mysql connectivity


Step 4 : Lets create fresh project for testing database testing. You can create Class in
existing project also.

Create project


Step 5 : Add MySql jar in the Build Path of the project
Step 6 : Follow below steps in the created class for performing below functions;



Select
Select with condition
Insert




import package java.sql.* : All database connectivity related classes are present here.
Add jar of mysql database connectivity
Interface Connection in java helps to connect to database . It has many methods



Above Driver does all the magic to connect
All database connectivity should be in try catch


Code Snippet

import java.sql.*;
public class dbconnectclass {
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException, SQLException{

//Below is standard variables which you need to set for database connectivity

Connection conn = null; //Create object of Connection object
String url = "jdbc:mysql://localhost:3306/";
String driver = "com.mysql.jdbc.Driver"; //different for Oracleor other databases
String dbname ="test";
String userName= "root";
String password ="password";


try {

Class.forName(driver).newInstance(); //create object of Driver class

conn=DriverManager.getConnection(url+dbname,userName,password); //connection
will be established from this line


//***********Statement***********Without condition Select Statement*********
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from users");
rs.next() ; //1st Row
System.out.println(rs.getString("name")); //column
rs.next() ; //2nd Row
System.out.println(rs.getString(1));
// to print whole table
// mind it rs is at the 3rd row.
while(rs.next()){
System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) );
}
//********Prepared statement**select**********
//Prepared Statement is used for sql statement with conditional statements
PreparedStatement pstmt= conn.prepareStatement("select * from users where name =
? and sex= ? ");
pstmt.setString(1, "B");
pstmt.setString(2, "F");
ResultSet rs1=pstmt.executeQuery();
while(rs1.next()){
System.out.println(rs1.getString(1) + " " + rs1.getString(2) + " " + rs1.getString(3) );
}
//********Prepared statement**insert**********
//Prepared Statement is used for sql statement with conditional statements
PreparedStatement pstmt1= conn.prepareStatement("insert into users values(?,?,?)");
pstmt1.setString(1, "Tom");
pstmt1.setString(2, "London");
pstmt1.setString(3, "M");
pstmt1.executeUpdate();
System.out.println("Inserted");
} catch (Exception e) {
}finally {
conn.close();
}
}
}


Maximising Window - Webdriver
package test;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class maximizewind {

public static void main(String[] args){

WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com/");
driver.manage().window().maximize();


}
}



Taking Screenshot - Webdriver
package test;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.internal.selenesedriver.TakeScreenshot;
public class takingscrshot {

public static void main(String[] args) throws IOException{

WebDriver driver= new FirefoxDriver();
driver.get("https://www.google.com/");

File scrFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("C:\\Local Disk D_9220122129\\tmp.jpg"));

}

}

Using Properties Class - WebDriver
How to get values from some Config/text files through Properties Class



Step 1 : Create file and put values like below in it and place it in some package.

e.g config.properties

firstname=harry
lastname=mohan


Step 2 : Use System.getProperty("user.dir") to get the relative path of workspace . This
way you can make config.properties as machine independent

Step 3 : Use below code . It has all detail about further steps

package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class propfilelearning {
public static void main(String[] args) throws IOException{

//Create Object of Properties Class

Properties prop = new Properties();

//Use System.getProperty to get the relative path of file in Workspace. Now file path is
machine independent.
String path = System.getProperty("user.dir") + "\\src\\test\\config.properties";
System.out.println("Actual Location of File -> " + path);


//Create FileInputStream object of Config/data file
FileInputStream fs= new FileInputStream(path);

// Pass fs object to load method of Properties object

prop.load(fs);

// Use getProperty method of Properties object to get the values.

System.out.println(prop.getProperty("firstname"));
System.out.println(prop.getProperty("lastname"));

}
}


Handling Proxies - WebDriver
I had to run the Webdriver scripts on a Firefox and I had to use a particular proxy to get
access to the
QA/Dev environment. Here is the code that you can use to change the proxy settings.


FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("network.proxy.type", 1);
firefoxProfile.setPreference("network.proxy.http", "100.00.100.100");
firefoxProfile.setPreference("network.proxy.http_port", 80);
firefoxProfile.setPreference("network.proxy.ssl", "100.00.100.100");
firefoxProfile.setPreference("network.proxy.ssl_port", 80);
firefoxProfile.setPreference("network.proxy.no_proxies_on", "");
driver = new FirefoxDriver(firefoxProfile);



Make changes to the PROXY_HOST 100.00.100.100 and the PROXY_PORT 80.
The PROXY_PORT is an Integer and PROXY_HOST is a String.


How to get title of Browser - Selenium
package test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class titlebrow {

public static void main(String[] args){

WebDriver driver = new FirefoxDriver();
driver.get("http://www.rediff.com/");
System.out.println("Title is : " + driver.getTitle());

}
}
Handling Alert in Java - Selenium
package test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class handlingalert {

public static void main(String[] args){

WebDriver driver = new FirefoxDriver();
driver.get("http://www.rediff.com/");
driver.findElement(By.xpath("//a[@title='Already a user? Sign in']")).click();
driver.findElement(By.xpath("//input[@id='btn_login']")).click();
driver.switchTo().alert().accept() ;

//If you want to do some operations or validations on alert below code is helpful
driver.findElement(By.xpath("//input[@id='btn_login']")).click();
Alert al = driver.switchTo().alert();
System.out.println(al.getText());
// al.dismiss(); //only if cancel is there . In our case cancel is not there.

}
}

Handling iFrame on WebPage - Selenium
Below Code Handles iFrame on one of the website


package test;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class iframelearn {
public static void main(String[] args ) throws InterruptedException{

WebDriver driver = new FirefoxDriver();
driver.get("http://borro.com/start");
driver.findElement(By.xpath("//a[@class='iframe-callback top-link-red']")).click();
Thread.sleep(1000L);
//Below listing of frame is done as we could not find iframe tag in the view source
List<WebElement> frames = driver.findElements(By.tagName("iFrame"));
System.out.println("Total Frames -> " + frames.size());
//Size of frames is 2 but we dont know which is our frame, so do hit and trial by finding
desired frame element . If not found on first try on second.In our case it is on second
frame.
driver.switchTo().frame(1);
//Enter into first element on the frame
driver.findElement(By.id("firstname")).sendKeys("Harpreat");
//If you want to get id of frames use below code. Position of code may be incorrect.
System.out.println(frames.get(0).getAttribute("id"));
System.out.println(frames.get(1).getAttribute("id"));

}
}



Extract all links from a webpage using webdriver for selenium automation testing
Extract all links from a webpage using webdriver for selenium automation testing

mport java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class dadabhagwan_LearnSeleniumWithJasmine {
public static void main(String[] args) throws InterruptedException {
WebDriver myDriver = new FirefoxDriver();
myDriver.get("http://satsang.dadabhagwan.org/");
/*Extract all links from the webpage using selenium webdriver*/
List all_links_webpage = myDriver.findElements(By.tagName("a"));
/*Print total no of links on the webpage*/
System.out.println("Print total no of links on the webpage-----------------------------------------
----");
System.out.println(all_links_webpage.size());
/*Print text of all links*/
System.out.println("Print text of all links------------------------------------------------------------");
for(int i=0;i
System.out.println(all_links_webpage.get(i).getText());
}
/*Print Links*/
System.out.println("Print Links------------------------------------------------------------------------");
for(int i=0;i
System.out.println(all_links_webpage.get(i).getAttribute("href"));
}

/*Extract all links from the part of the webpage using selenium webdriver*/
System.out.println("Extract all links from the part of the webpage using selenium
webdriver-----------------------------");
List myList =
myDriver.findElement(By.xpath("//*[@id='Flot']")).findElements(By.tagName("a"));
System.out.println("total no links on specific part of webpage------------------------------------
---------------");
System.out.println(myList.size());
System.out.println("Text of the link for specific part of webpage---------------------------------
-----------------");
for(int i =0; i< myList.size();i++){
System.out.println(myList.get(i).getText());
}
}
}

Pausing Execution - Thread.sleep(time)

Use below statement in you code if you want to pause execution of your run.

Thread.sleep(4000) ; //for 4 seconds

Note : Above statment throws "InterruptedException" , so need to handle in the
method.



Selenium Grid Installations

Download Required

1) selenium-server-standalone-ver.jar : All client machines and Server Machine


Steps :

Step 1 : Start the hub : Start hub on the Server machine with below command

java -jar selenium-server-standalone-2.28.0.jar -role hub

The hub will automatically start-up using port 4444 by default. To change the default
port, you can add the optional parameter -port when you run the command. You can
view the status of the hub by opening a browser window and navigating
to: http://localhost:4444/grid/console

Step 2: Start the nodes : Regardless on whether you want to run a grid with new
WebDriver functionality, or a grid with Selenium 1 RC functionality, or both at the same
time, you use the same selenium-server-standalone jar file to start the nodes.

java -jar selenium-server-standalone-2.14.0.jar -role node -hub
http://localhost:4444/grid/register

-browser browserName=firefox,version=3.6,maxInstances=5,platform=LINUX : This
can be supplied .
For Windows : platform=WINDOWS
Note: The port defaults to 5555 if not specified whenever the "-role" option is provided
and is not hub.



USING GRID TO RUN TESTS

FOR WEBDRIVER NODES, YOU WILL NEED TO USE
THE REMOTEWEBDRIVER AND THE DESIREDCAPABILITIES OBJECT TO
DEFINE WHICH BROWSER, VERSION AND PLATFORM YOU WISH TO USE.
CREATE THE TARGET BROWSER CAPABILITIES YOU WANT TO RUN THE
TESTS AGAINST:

DESIREDCAPABILITIES CAPABILITY = DESIREDCAPABILITIES.FIREFOX();

Pass that into the RemoteWebDriver object:
WebDriver driver = new RemoteWebDriver(new
URL("http://localhost:4444/wd/hub"), capability);
The hub will then assign the test to a matching node.
A node matches if all the requested capabilities are met. To request specific capabilities
on the grid, specify them before passing it into the WebDriver object.
capability.setBrowserName();
capability.setPlatform();
capability.setVersion()
capability.setCapability(,);
Example: A node registered with the setting:
-browser browserName=firefox,version=3.6,platform=LINUX
will be a match for:
capability.setBrowserName(firefox );
capability.setPlatform(LINUX);
capability.setVersion(3.6);
and would also be a match for
capability.setBrowserName(firefox );
capability.setVersion(3.6);
CODE SNIPPET :
IMPORT J AVA.NET.MALFORMEDURLEXCEPTION;
IMPORT J AVA.NET.URL;


IMPORT ORG.OPENQA.SELENIUM.WEBDRIVER;
IMPORT ORG.OPENQA.SELENIUM.REMOTE.DESIREDCAPABILITIES;
IMPORT ORG.OPENQA.SELENIUM.REMOTE.REMOTEWEBDRIVER;
IMPORT ORG.TESTNG.ANNOTATIONS.TEST;


PUBLIC CLASS TESTREMOTE {

@TEST
PUBLIC VOID TEST1() THROWS MALFORMEDURLEXCEPTION{

DESIREDCAPABILITIES CAPABILITY =DESIREDCAPABILITIES.FIREFOX();
CAPABILITY.SETBROWSERNAME("FIREFOX");
CAPABILITY.SETVERSION("18.0.2");
WEBDRIVER DRIVER =NEW REMOTEWEBDRIVER(NEW
URL("HTTP://LOCALHOST:4444/WD/HUB"), CAPABILITY);
DRIVER.GET("HTTP://GOOGLE.COM");


}

}



Reading and Writing in Excel

package excel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;

/**
* A simple POI example of opening an Excel spreadsheet
* and writing its contents to the command line.
* @author Tony Sintes
*/
public class POIExample {

public static void main(String[] args) {
String fileName = "C:\\testPOIWrite.xls";
writeDataToExcelFile(fileName);
readDataToExcelFile(fileName);
}

public static void readDataToExcelFile(String fileName){
try{
FileInputStream fis = new FileInputStream(fileName);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);

for (int rowNum = 0; rowNum < 10; rowNum++) {
for (int cellNum = 0; cellNum < 5; cellNum++) {
HSSFCell cell =
sheet.getRow(rowNum).getCell(cellNum);
System.out.println(rowNum+":"+cellNum+" = "
+ cell.getStringCellValue());
}
}

fis.close();
}catch(Exception e){
e.printStackTrace();
}


}
public static void writeDataToExcelFile(String fileName) {
try {

HSSFWorkbook myWorkBook = new HSSFWorkbook();
HSSFSheet mySheet = myWorkBook.createSheet();
HSSFRow myRow;
HSSFCell myCell;

for (int rowNum = 0; rowNum < 10; rowNum++) {
myRow = mySheet.createRow(rowNum);
for (int cellNum = 0; cellNum < 5; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(new
HSSFRichTextString(rowNum + "," + cellNum));
}
}


FileOutputStream out = new
FileOutputStream(fileName);
myWorkBook.write(out);
out.flush();
out.close();


} catch (Exception e) {
e.printStackTrace();
}
}
}



WebDriverWait(Handles AJAX) Fundamental - Selenium


public class testclass {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");


// Below is one way of implemening
WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(new
ExpectedCondition<WebElement>(){
@Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("myDynamicElement"));
}});

//Second easy way of implementing
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element =
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("someid")));

}}



}}

Above is explicit wait where you define code to wait for a certain condition to occur
before proceeding further in the code. WebDriverWait in combination
with ExpectedCondition is one way this can be accomplished.

This waits up to 10 seconds before throwing a TimeoutException or if it finds the
element will return it in 0 - 10 seconds.WebDriverWait by default calls the
ExpectedCondition every 500 milliseconds until it returns successfully. A successful
return is for ExpectedCondition type is Boolean return true or not null return value for all
other ExpectedCondition types.


Expected Condition : There are some common conditions that are frequently come
across when automating web browsers. Listed below are Implementations of each. Java
happens to have convienence methods so you dont have to code an
ExpectedCondition class yourself or create your own utility package for them. Refer
below for some of the condition

http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/support/ui
/ExpectedConditions.html

JAVA CASTING


GETTING A STRING OUT OF AN ARRAYLIST

String StringName = (String)arrayListName.get(n);


Note : Double is a class while double is a primitive
GETTING A DOUBLE OUT OF AN ARRAYLIST (STORED IN THE ARRAYLIST AS A DOUBLE)

double doubName = ((Double)arrayListName.get(n)).doubleValue();



STRING TO DOUBLE TO DOUBLE (USING DOUBLE CONSTRUCTOR)

double doubName = new Double(stringName).doubleValue;
STRING TO DOUBLE TO DOUBLE

double doubName = Double.valueOf(stringName).doubleValue;
STRING TO DOUBLE (USING STATIC DOUBLE METHOD - JAVA 1.2 & LATER)

double doubName = Double.parseDouble(stringName);
DOUBLE TO A NEW STRING (USING THE STRING CONSTRUCTOR)

String stringName = new String(doubleName);
DOUBLE TO EXISTING STRING

stringName = String.valueOf(doubleName);
DOUBLE TO INT

double doubleName = 3;
int intName = (int)doubleName;
// intName becomes == 3
double anotherDoubleName = 3.3;
int anotherIntName = (int)anotherDoubleName;
//anotherIntName becomes == 3, not 3.3
STRING TO CHAR

char charName = stringName.charAt(2);
//must specify offset in string to get char from

TestNG Tutorial - I
TestNG is a testing framework designed to simply 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).

Writing a test is typically a three-step process:
Write the business logic of your test and insert TestNG annotations in your code.
Add the information about your test (e.g. the class name, the groups you wish to run,
etc...) in a testng.xml file or in build.xml.
Run TestNG.


You can find a quick example on the Welcome page.
The concepts used in this documentation are as follows:
A suite is represented by one XML file. It can contain one or more tests and is
defined by the <suite> tag.
A test is represented by <test> and can contain one or more TestNG classes.
A TestNG class is a Java class that contains at least one TestNG annotation. It is
represented by the <class> tag and can contain one or more test methods.
A test method is a Java method annotated by @Test in your source.


Question : What kind of method on Before Suite and After suite ?

You can invoke TestNG in several different ways:
With a testng.xml file
With ant
From the command line

The current DTD for testng.xml can be found on the main Web
site: http://testng.org/testng-1.0.dtd (for your convenience, you might prefer to browse
the HTML version).


TestNG can be invoked in different ways:
Command line
ant
Eclipse
IntelliJ's IDEA

Assuming that you have TestNG in your class path, the simplest way to invoke TestNG
is as follows:
java org.testng.TestNG testng1.xml [testng2.xml testng3.xml ...]

You need to specify at least one XML file describing the TestNG suite you are trying to
run. Additionally, the following command-line switches are available:

Option Argument Documentation
-configfailurepolicy skip|continue Whether TestNG should continue to execute the
remaining tests in the suite or skip them if an @Before* method fails. Default behavior is
skip.
-d A directory The directory where the reports will be generated (defaults to test-
output).
-dataproviderthreadcount The default number of threads to use for data providers
when running tests in parallel. This sets the default maximum number of threads to
use for data providers when running tests in parallel. It will only take effect if the parallel
mode has been selected (for example, with the -parallel option). This can be overridden
in the suite definition.
-excludegroups A comma-separated list of groups. The list of groups you want to be
excluded from this run.
-groups A comma-separated list of groups. The list of groups you want to run (e.g.
"windows,linux,regression").
-listener A comma-separated list of Java classes that can be found on your
classpath. Lets you specify your own test listeners. The classes need to implement
org.testng.ITestListener

-methods A comma separated list of fully qualified class name and method. For
example com.example.Foo.f1,com.example.Bar.f2. Lets you specify individual
methods to run.
-methodselectors A comma-separated list of Java classes and method priorities that
define method selectors. Lets you specify method selectors on the command line. For
example: com.example.Selector1:3,com.example.Selector2:2
-parallel methods|tests|classes If specified, sets the default mechanism used to
determine how to use parallel threads when running tests. If not set, default mechanism
is not to use parallel threads at all. This can be overridden in the suite definition.
-reporter The extended configuration for a custom report listener. Similar to the -
listener option, except that it allows the configuration of JavaBeans-style properties on
the reporter instance.
Example: -reporter com.test.MyReporter:methodFilter=*insert*,enableFiltering=true
You can have as many occurences of this option, one for each reporter that needs to be
added.
-sourcedir A semi-colon separated list of directories. The directories where your
javadoc annotated test sources are. This option is only necessary if you are using
javadoc type annotations. (e.g. "src/test" or "src/test/org/testng/eclipse-
plugin;src/test/org/testng/testng").
-suitename The default name to use for a test suite. This specifies the suite name
for a test suite defined on the command line. This option is ignored if the suite.xml file or
the source code specifies a different suite name. It is possible to create a suite name
with spaces in it if you surround it with double-quotes "like this".
-testclass A comma-separated list of classes that can be found in your classpath. A
list of class files separated by commas (e.g. "org.foo.Test1,org.foo.test2").
-testjar A jar file. Specifies a jar file that contains test classes. If a testng.xml file is
found at the root of that jar file, it will be used, otherwise, all the test classes found in
this jar file will be considered test classes.
-testname The default name to use for a test. This specifies the name for a test
defined on the command line. This option is ignored if the suite.xml file or the source
code specifies a different test name. It is possible to create a test name with spaces in it
if you surround it with double-quotes "like this".
-testnames A comma separated list of test names. Only tests defined in a <test> tag
matching one of these names will be run.
-testrunfactory A Java classes that can be found on your classpath. Lets you specify
your own test runners. The class needs to implement org.testng.ITestRunnerFactory.

-threadcount The default number of threads to use when running tests in
parallel. This sets the default maximum number of threads to use for running tests in
parallel. It will only take effect if the parallel mode has been selected (for example, with
the -parallel option). This can be overridden in the suite definition.
-xmlpathinjar The path of the XML file inside the jar file. This attribute should contain
the path to a valid XML file inside the test jar (e.g. "resources/testng.xml"). The default
is "testng.xml", which means a file called "testng.xml" at the root of the jar file. This
option will be ignored unless -testjar is specified.
This documentation can be obtained by invoking TestNG without any arguments.


You can also put the command line switches in a text file, say c:\command.txt, and tell
TestNG to use that file to retrieve its parameters:
C:> more c:\command.txt
-d test-output testng.xml
C:> java org.testng.TestNG @c:\command.txt



Note: TestNG uses regular expressions, and not wildmats. Be aware of the difference
(for example, "anything" is matched by ".*" -- dot star -- and not "*").

5.1 - Test groups

TestNG allows you to perform sophisticated groupings of test methods. Not only can
you declare that methods belong to groups, but you can also specify groups that contain
other groups. Then TestNG can be invoked and asked to include a certain set of groups
(or regular expressions) while excluding another set. This gives you maximum flexibility
in how you partition your tests and doesn't require you to recompile anything if you want
to run two different sets of tests back to back.
Groups are specified in your testng.xml file and can be found either under the <test> or
<suite> tag. Groups specified in the <suite> tag apply to all the <test> tags underneath.
Note that groups are accumulative in these tags: if you specify group "a" in <suite> and
"b" in <test>, then both "a" and "b" will be included.
For example, it is quite common to have at least two categories of tests
Check-in tests. These tests should be run before you submit new code. They
should typically be fast and just make sure no basic functionality was broken.

Functional tests. These tests should cover all the functionalities of your software
and be run at least once a day, although ideally you would want to run them
continuously.
Typically, check-in tests are a subset of functional tests. TestNG allows you to specify
this in a very intuitive way with test groups. For example, you could structure your test
by saying that your entire test class belongs to the "functest" group, and additionally that
a couple of methods belong to the group "checkintest":
Test1.java
view source
print?
public class Test1 {
@Test(groups = { "functest", "checkintest" })
public void testMethod1() {
}

@Test(groups = {"functest", "checkintest"} )
public void testMethod2() {
}

@Test(groups = { "functest" })
public void testMethod3() {
}
}
Invoking TestNG with
testng.xml
<test name="Test1">
<groups>
<run>
<include name="functest"/>
</run>
</groups>
<classes>
<class name="example1.Test1"/>
</classes>
</test>
will run all the test methods in that classes, while invoking it with checkintest will only
run testMethod1() and testMethod2().
Here is another example, using regular expressions this time. Assume that some of
your test methods should not be run on Linux, your test would look like:
Test1.java
@Test
public class Test1 {
@Test(groups = { "windows.checkintest" })
public void testWindowsOnly() {
}

@Test(groups = {"linux.checkintest"} )
public void testLinuxOnly() {
}

@Test(groups = { "windows.functest" )
public void testWindowsToo() {
}
}
You could use the following testng.xml to launch only the Windows methods:
testng.xml
view source
print?
<test name="Test1">
<groups>
<run>
<include name="windows.*"/>
</run>
</groups>

<classes>
<class name="example1.Test1"/>
</classes>
</test>
Note: TestNG uses regular expressions, and not wildmats. Be aware of the difference
(for example, "anything" is matched by ".*" -- dot star -- and not "*").


Method groups
You can also exclude or include individual methods:
testng.xml
view source
print?
<test name="Test1">
<classes>
<class name="example1.Test1">
<methods>
<include name=".*enabledTestMethod.*"/>
<exclude name=".*brokenTestMethod.*"/>
</methods>
</class>
</classes>
</test>
This can come in handy to deactivate a single method without having to recompile
anything, but I don't recommend using this technique too much since it makes your
testing framework likely to break if you start refactoring your Java code (the regular
expressions used in the tags might not match your methods any more).


5.3 - Exclusion group


All I need to do now is to exclude this group from the run:
testng.xml
view source
print?
<test name="Simple example">
<groups>
<run>
<include name="checkintest"/>
<exclude name="broken"/>
</run>
</groups>

<classes>
<class name="example1.Test1"/>
</classes>
</test>


5.4 - Partial groups
You can define groups at the class level and then add groups at the method level:
All.java
view source
print?
@Test(groups = { "checkin-test" })
public class All {

@Test(groups = { "func-test" )
public void method1() { ... }

public void method2() { ... }
}
In this class, method2() is part of the group "checkin-test", which is defined at the class
level, while method1() belongs to both "checkin-test" and "func-test".


5.5 - Parameters
Test methods don't have to be parameterless. You can use an arbitrary number of
parameters on each of your test method, and you instruct TestNG to pass you the
correct parameters with the @Parameters annotation.
There are two ways to set these parameters: with testng.xml or programmatically.
5.5.1 - Parameters from testng.xml
If you are using simple values for your parameters, you can specify them in your
testng.xml:
Java
view source
print?
@Parameters({ "first-name" })
@Test
public void testSingleString(String firstName) {
System.out.println("Invoked testString " + firstName);
assert "Cedric".equals(firstName);
}
In this code, we specify that the parameter firstName of your Java method should
receive the value of the XML parameter called first-name. This XML parameter is
defined in testng.xml:
testng.xml
view source
print?
<suite name="My suite">
<parameter name="first-name" value="Cedric"/>
<test name="Simple example">
<-- ... -->
The same technique can be used for @Before/After and @Factory annotations:
view source
print?
@Parameters({ "datasource", "jdbcDriver" })
@BeforeMethod
public void beforeTest(String ds, String driver) {
m_dataSource = ...; // look up the value of datasource
m_jdbcDriver = driver;
}
This time, the two Java parameter ds and driver will receive the value given to the
properties datasource and jdbc-driver respectively.
Parameters can be declared optional with the Optional annotation:
view source
print?
@Parameters("db")
@Test
public void testNonExistentParameter(@Optional("mysql") String db) { ... }
If no parameter named "db" is found in your testng.xml file, your test method will receive
the default value specified inside the @Optional annotation: "mysql".
The @Parameters annotation can be placed at the following locations:
On any method that already has a @Test, @Before/After or @Factory annotation.
On at most one constructor of your test class. In this case, TestNG will invoke this
particular constructor with the parameters initialized to the values specified in testng.xml
whenever it needs to instantiate your test class. This feature can be used to initialize
fields inside your classes to values that will then be used by your test methods.
Notes:
The XML parameters are mapped to the Java parameters in the same order as they
are found in the annotation, and TestNG will issue an error if the numbers don't match.
Parameters are scoped. In testng.xml, you can declare them either under a <suite>
tag or under <test>. If two parameters have the same name, it's the one defined in
<test> that has precedence. This is convenient if you need to specify a parameter
applicable to all your tests and override its value only for certain tests.


5.6 - Dependent methods
Sometimes, you need your test methods to be invoked in a certain order. This is useful
for example
To make sure a certain number of test methods have completed and succeeded
before running more test methods.
To initialize your tests while wanting this initialization methods to be test methods as
well (methods tagged with @Before/After will not be part of the final report).
In order to do this, you can use the attributes dependsOnMethods or
dependsOnGroups, found on the @Test annotation.
There are two kinds of dependencies:
Hard dependencies. All the methods you depend on must have run and succeeded
for you to run. If at least one failure occurred in your dependencies, you will not be
invoked and marked as a SKIP in the report.
Soft dependencies. You will always be run after the methods you depend on, even if
some of them have failed. This is useful when you just want to make sure that your test
methods are run in a certain order but their success doesn't really depend on the
success of others. A soft dependency is obtained by adding "alwaysRun=true" in your
@Test annotation.
Here is an example of a hard dependency:
view source
print?
@Test
public void serverStartedOk() {}

@Test(dependsOnMethods = { "serverStartedOk" })
public void method1() {}
In this example, method1() is declared as depending on method serverStartedOk(),
which guarantees that serverStartedOk() will always be invoked first.
You can also have methods that depend on entire groups:
view source
print?
@Test(groups = { "init" })
public void serverStartedOk() {}

@Test(groups = { "init" })
public void initEnvironment() {}

@Test(dependsOnGroups = { "init.* })
public void method1() {}
In this example, method1() is declared as depending on any group matching the regular
expression "init.*", which guarantees that the methods serverStartedOk() and
initEnvironment() will always be invoked before method1().
Note: as stated before, the order of invocation for methods that belong in the same
group is not guaranteed to be the same across test runs.
If a method depended upon fails and you have a hard dependency on it
(alwaysRun=false, which is the default), the methods that depend on it are not marked
as FAIL but as SKIP. Skipped methods will be reported as such in the final report (in a
color that is neither red nor green in HTML), which is important since skipped methods
are not necessarily failures.
Both dependsOnGroups and dependsOnMethods accept regular expressions as
parameters. For dependsOnMethods, if you are depending on a method which
happens to have several overloaded versions, all the overloaded methods will be
invoked. If you only want to invoke one of the overloaded methods, you should use
dependsOnGroups.


5.8 - Class level annotations
The @Test annotation can be put on a class instead of a test method:
Test1.java
view source
print?
@Test
public class Test1 {
public void test1() {
}

public void test2() {
}
}
The effect of a class level @Test annotation is to make all the public methods of this
class to become test methods even if they are not annotated. You can still repeat the
@Test annotation on a method if you want to add certain attributes.
For example:
Test1.java
view source
print?
@Test
public class Test1 {
public void test1() {
}

@Test(groups = "g1")
public void test2() {
}
}
will make both test1() and test2() test methods but on top of that, test2() now belongs to
the group "g1".


5.9 - Parallelism and time-outs
You can instruct TestNG to run your tests in separate threads in various ways.
5.9.1 - Parallel suites
This is useful if you are running several suite files (e.g. "java org.testng.TestNG
testng1.xml testng2.xml") and you want each of these suites to be run in a separate
thread. You can use the following command line flag to specify the size of a thread pool:
view source
print?
java org.testng.TestNG -suitethreadpoolsize 3 testng1.xml testng2.xml testng3.xml
The corresponding ant task name is suitethreadpoolsize.
5.9.2 - Parallel tests, classes and methods
The parallel attribute on the <suite> tag can take one of following values:
view source
print?
<suite name="My suite" parallel="methods" thread-count="5">
view source
print?
<suite name="My suite" parallel="tests" thread-count="5">
view source
print?
<suite name="My suite" parallel="classes" thread-count="5">
parallel="methods": TestNG will run all your test methods in separate threads.
Dependent methods will also run in separate threads but they will respect the order that
you specified.

parallel="tests": TestNG will run all the methods in the same <test> tag in the same
thread, but each <test> tag will be in a separate thread. This allows you to group all
your classes that are not thread safe in the same <test> and guarantee they will all run
in the same thread while taking advantage of TestNG using as many threads as
possible to run your tests.

parallel="classes": TestNG will run all the methods in the same class in the same
thread, but each class will be run in a separate thread.
Additionally, the attribute thread-count allows you to specify how many threads should
be allocated for this execution.
Note: the @Test attribute timeOut works in both parallel and non-parallel mode.
You can also specify that a @Test method should be invoked from different threads.
You can use the attribute threadPoolSize to achieve this result:
view source
print?
@Test(threadPoolSize = 3, invocationCount = 10, timeOut = 10000)
public void testServer() {
In this example, the function testServer will be invoked ten times from three different
threads. Additionally, a time-out of ten seconds guarantees that none of the threads will
block on this thread forever.


5.10 - Rerunning failed tests
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, allowing you to quickly reproduce the failures without having to run
the entirety of your tests. Therefore, a typical session would look like this:
view source
print?
java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -d test-outputs
testng.xml
java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -d test-outputs test-
outputs\testng-failed.xml
Note that testng-failed.xml will contain all the necessary dependent methods so that you
are guaranteed to run the methods that failed without any SKIP failures.



5.11 - JUnit tests
TestNG can run JUnit 3 tests (JUnit 4 is not supported). All you need to do is specify
your JUnit test classes in the testng.classNames property and set the testng.junit
property to true:
testng.xml
view source
print?
<test name="Test1" junit="true">
<classes>
<!-- ... -->
The behavior of TestNG in this case is similar to JUnit:
All methods starting with test* in your classes will be run
If there is a method setUp() on your test class, it will be invoked before every test
method
If there is a method tearDown() on your test class, it will be invoked before after
every test method
If your test class contains a method suite(), all the tests returned by this method will
be invoked


6 - Test results
6.1 - Success, failure and assert
A test is considered successful if it completed without throwing any exception or if it
threw an exception that was expected (see the documentation for the
expectedExceptions attribute found on the @Test annotation).
Your test methods will typically be made of calls that can throw an exception, or of
various assertions (using the Java "assert" keyword). An "assert" failing will trigger an
AssertionErrorException, which in turn will mark the method as failed (remember to use
-ea on the JVM if you are not seeing the assertion errors).
Here is an example test method:
view source
print?
@Test
public void verifyLastName() {
assert "Beust".equals(m_lastName) : "Expected name Beust, for" + m_lastName;
}
TestNG also include JUnit's Assert class, which lets you perform assertions on complex
objects:
view source
print?
import static org.testng.AssertJUnit.*;
//...
@Test
public void verify() {
assertEquals("Beust", m_lastName);
}
Note that the above code use a static import in order to be able to use the assertEquals
method without having to prefix it by its class.


6.2 - Logging and results
The results of the test run are created in a file called index.html in the directory specified
when launching SuiteRunner. This file points to various other HTML and text files that
contain the result of the entire test run. You can see a typical example here.
It's very easy to generate your own reports with TestNG with Listeners and Reporters:
Listeners implement the interface org.testng.ITestListener and are notified in real
time of when a test starts, passes, fails, etc...
Reporters implement the interface org.testng.IReporter and are notified when all the
suites have been run by TestNG. The IReporter instance receives a list of objects that
describe the entire test run.
For example, if you want to generate a PDF report of your test run, you don't need to be
notified in real time of the test run so you should probably use an IReporter. If you'd like
to write a real-time reporting of your tests, such as a GUI with a progress bar or a text
reporter displaying dots (".") as each test is invoked (as is explained below),
ITestListener is your best choice.
6.2.1 - Logging Listeners
Here is a listener that displays a "." for each passed test, a "F" for each failure and a "S"
for each skip:
view source
print?
public class DotTestListener extends TestListenerAdapter {
private int m_count = 0;

@Override
public void onTestFailure(ITestResult tr) {
log("F");
}

@Override
public void onTestSkipped(ITestResult tr) {
log("S");
}

@Override
public void onTestSuccess(ITestResult tr) {
log(".");
}

private void log(String string) {
System.out.print(string);
if (++m_count % 40 == 0) {
System.out.println("");
}
}
}
In this example, I chose to extend TestListenerAdapter, which implements ITestListener
with empty methods, so I don't have to override other methods from the interface that I
have no interest in. You can implement the interface directly if you prefer.
Here is how I invoke TestNG to use this new listener:
Shell
view source
print?
java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -listener
org.testng.reporters.DotTestListener test\testng.xml
and the output:
Shell
view source
print?
........................................
........................................
........................................
........................................
........................................
.........................
===============================================
TestNG JDK 1.5
Total tests run: 226, Failures: 0, Skips: 0
===============================================
Note that when you use -listener, TestNG will automatically determine the type of
listener you want to use.
6.2.2 - Logging Reporters
The org.testng.IReporter interface only has one method:
view source
print?
public void generateReport(List<ISuite> suites, String outputDirectory)
This method will be invoked by TestNG when all the suites have been run and you can
inspect its parameters to access all the information on the run that was just completed.
6.2.3 - JUnitReport
TestNG contains a listener that takes the TestNG results and outputs an XML file that
can then be fed to JUnitReport. Here is an example, and the ant task to create this
report:
build.xml
view source
print?
<target name="reports">
<junitreport todir="test-report">
<fileset dir="test-output">
<include name="*/*.xml"/>
</fileset>

<report format="noframes" todir="test-report"/>
</junitreport>
</target>
Note: a current incompatibility between the JDK 1.5 and JUnitReports prevents the
frame version from working, so you need to specify "noframes" to get this to work for
now.
6.2.4 - Reporter API
If you need to log messages that should appear in the generated HTML reports, you
can use the class org.testng.Reporter:
Reporter.log("M3 WAS CALLED");
TestNG Tutorial

TESTNG TUTORIAL 1 BASIC USAGE

This tutorial introduces the basic annotation supported in TestNG.
import java.util.*;
import org.testng.Assert;
import org.testng.annotations.*;

public class TestNGTest1 {

private Collection collection;

@BeforeClass
public void oneTimeSetUp() {
// one-time initialization code
System.out.println("@BeforeClass - oneTimeSetUp");
}

@AfterClass
public void oneTimeTearDown() {
// one-time cleanup code
System.out.println("@AfterClass - oneTimeTearDown");
}

@BeforeMethod
public void setUp() {
collection = new ArrayList();
System.out.println("@BeforeMethod - setUp");
}

@AfterMethod
public void tearDown() {
collection.clear();
System.out.println("@AfterMethod - tearDown");
}

@Test
public void testEmptyCollection() {
Assert.assertEquals(collection.isEmpty(),true);
System.out.println("@Test - testEmptyCollection");
}

@Test
public void testOneItemCollection() {
collection.add("itemA");
Assert.assertEquals(collection.size(),1);
System.out.println("@Test - testOneItemCollection");
}
}
Result
@BeforeClass - oneTimeSetUp
@BeforeMethod - setUp
@Test - testEmptyCollection
@AfterMethod - tearDown
@BeforeMethod - setUp
@Test - testOneItemCollection
@AfterMethod - tearDown
@AfterClass - oneTimeTearDown
PASSED: testEmptyCollection
PASSED: testOneItemCollection

TESTNG TUTORIAL 2 EXPECTED EXCEPTION TEST

import org.testng.annotations.*;

/**
* TestNG Expected Exception Test
* @author mkyong
*
*/
public class TestNGTest2 {

@Test(expectedExceptions = ArithmeticException.class)
public void divisionWithException() {
int i = 1/0;
}

}
In above example, the divisionWithException() method will throw an
ArithmeticException Exception, since this is an expected exception, so the unit test will
pass.
TESTNG TUTORIAL 3 IGNORE TEST

This Ignored means the method is not ready to test, the TestNG engine will just
bypass this method.
import org.testng.annotations.*;

/**
* TestNG Ignore Test
* @author mkyong
*
*/
public class TestNGTest3 {

@Test(enabled=false)
public void divisionWithException() {
System.out.println("Method is not ready yet");
}

}
In above example, TestNG will not test the divisionWithException() method.


TESTNG TUTORIAL 4 TIME TEST

The Time Test means if an unit test takes longer than the specified number of
milliseconds to run, the test will terminated and mark as failed.
import org.testng.annotations.*;

/**
* TestNG TimeOut Test
* @author mkyong
*
*/
public class TestNGTest4 {

@Test(timeOut = 1000)
public void infinity() {
while (true);
}

}
In above example, the infinity() method will not return, so the TestNG engine will mark it
as failed and throw an exception
FAILED: infinity
org.testng.internal.thread.ThreadTimeoutException:
Method public void TestNGTest4.infinity() didn't finish within the time-out 1000
... Removed 18 stack frames


TESTNG TUTORIAL 5 SUITE TEST

The Suite Test means bundle a few unit test cases and run it together.
In TestNG, XML file is use to define the suite test. The below XML file means both unit
test TestNGTest1 and TestNGTest2 will execute together.


<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="My test suite">
<test name="testing">
<classes>
<class name="TestNGTest1" />
<class name="TestNGTest2" />
</classes>
</test>
</suite>



Beside classes bundle testing, TestNG provides a Grouping feature to bundle few
methods as a single unit for testing, where every method is tie to a group.
For example, Heres a class with four methods, three groups (method1, method2 and
method3)
import org.testng.annotations.*;

/**
* TestNG Grouping
* @author mkyong
*
*/
public class TestNGTest5_2_0 {

@Test(groups="method1")
public void testingMethod1() {
System.out.println("Method - testingMethod1()");
}

@Test(groups="method2")
public void testingMethod2() {
System.out.println("Method - testingMethod2()");
}

@Test(groups="method1")
public void testingMethod1_1() {
System.out.println("Method - testingMethod1_1()");
}

@Test(groups="method4")
public void testingMethod4() {
System.out.println("Method - testingMethod4()");
}
}
You can execute the unit test with group method1 only.


<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="My test suite">
<test name="testing">
<groups>
<run>
<include name="method1"/>
</run>
</groups>
<classes>
<class name="TestNGTest5_2_0" />
</classes>
</test>
</suite>





TESTNG TUTORIAL 6 PARAMETERIZED TEST
The Parameterized Test means vary parameter value for unit test.

In TestNG,

XML file or
@DataProvider

is used to provide vary parameter for unit testing.


1. XML file for parameterized test.

Declare @Parameters annotation in method which needs parameter testing, the
parametric data will be provide by TestNGs XML configuration files. By doing this, you
can reuse a single test case with different data sets easily. In addition, even end user,
QA or QE can provide their own data sets for testing.
import org.testng.annotations.*;

/**
* TestNG Parameterized Test
* @author mkyong
*
*/
public class TestNGTest6_1_0 {

@Test
@Parameters(value="number")
public void parameterIntTest(int number) {
System.out.println("Parameterized Number is : " + number);
}
}


<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="My test suite">
<test name="testing">

<parameter name="number" value="2"/>

<classes>
<class name="TestNGTest6_1_0" />
</classes>
</test>
</suite>





2. @DataProvider for parameterized test.

While pulling data values into an XML file can be quite handy, but test cases
occasionally may require complex data types, which cant be represented as a String or
a primitive value in XML file. TestNG handles this scenario with@DataProvider
annotation, which facilitates the mapping of complex parameter types to a test method.

1. @DataProvider for Vector, String or Integer as parameter

import java.util.Vector;
import org.testng.annotations.*;

/**
* TestNG Parameterized Test - Advance
* @author mkyong
*
*/
public class TestNGTest6_2 {


@Test(dataProvider = "Data-Provider-Function")
public void parameterIntTest(Class clzz, String[] number) {
System.out.println("Parameterized Number is : " + number[0]);
System.out.println("Parameterized Number is : " + number[1]);
}

//This function will provide the parameter data
@DataProvider(name = "Data-Provider-Function")
public Object[][] parameterIntTestProvider() {
return new Object[][]{
{Vector.class, new String[] {"java.util.AbstractList",
"java.util.AbstractCollection"}},
{String.class, new String[] {"1", "2"}},
{Integer.class, new String[] {"1", "2"}}
};
}
}
Result
Parameterized Number is : java.util.AbstractList
Parameterized Number is : java.util.AbstractCollection
Parameterized Number is : 1
Parameterized Number is : 2
Parameterized Number is : 1
Parameterized Number is : 2
PASSED: parameterIntTest(class java.util.Vector, [Ljava.lang.String;@1016632)
PASSED: parameterIntTest(class java.lang.String, [Ljava.lang.String;@10a6ae2)
PASSED: parameterIntTest(class java.lang.Integer, [Ljava.lang.String;@4a6cbf)



2. @DataProvider for object as parameter

TestNGTest6_3_0 is a simple object with simple get set methods.
/**
* TestNG Parameterized Test - Advance
* @author mkyong
*
*/
public class TestNGTest6_3_0 {

private int number;
private String msg;

public void setNumber(int number){
this.number = number;
}

public int getNumber(){
return this.number;
}

public void setMsg(String msg){
this.msg = msg;
}

public String getMsg(){
return this.msg;
}

}
import org.testng.annotations.*;

/**
* TestNG Parameterized Test - Advance
* @author mkyong
*
*/
public class TestNGTest6_3_1 {

@Test(dataProvider = "Data-Provider-Function")
public void parameterIntTest(TestNGTest6_3_0 clzz) {
System.out.println("Parameterized Number is : " + clzz.getMsg());
System.out.println("Parameterized Number is : " + clzz.getNumber());
}

//This function will provide the patameter data
@DataProvider(name = "Data-Provider-Function")
public Object[][] parameterIntTestProvider() {

TestNGTest6_3_0 obj = new TestNGTest6_3_0();
obj.setMsg("Hello");
obj.setNumber(123);

return new Object[][]{
{obj}
};
}
}
Result
Parameterized Number is : 123
PASSED: parameterIntTest(TestNGTest6_3_0@dc6a77)
TestNGs Parameterized test is very user friendly and flexible (either in XML file or
inside the class). It can support many complex data type as parameter value and the
possibility is unlimited. As example above, you even can pass in your own object
(TestNGTest6_3_0) for Parameterized test.


TestNG parameter testing example
Published: December 1, 2009 , Updated: April 1, 2010 , Author: mkyong
print
TestNG parameter testing example.
Problem
Lets say, a utility class has a function for converting the character to ASCII or vice
verse, how can you test it with TestNG?
Solution
You can create a unit test function which accept two parameters (character and
expected ASCII) from TestNG data provider, and assert the value like following :
Example in Java
package com.mkyong.common;
/**
* Character Utility class
* @author mkyong
*
*/
public class CharUtils
{
/**
* Convert the characters to ASCII value
* @param character character
* @return ASCII value
*/
public static int CharToASCII(final char character){
return (int)character;
}

/**
* Convert the ASCII value to character
* @param ascii ascii value
* @return character value
*/
public static char ASCIIToChar(final int ascii){
return (char)ascii;
}
}
Unit Test
package com.mkyong.common;
import org.testng.Assert;
import org.testng.annotations.*;
/**
* Character Utils Testing
* @author mkyong
*
*/
public class CharUtilsTest {

@DataProvider
public Object[][] ValidDataProvider() {
return new Object[][]{
{ 'A', 65 },{ 'a', 97 },
{ 'B', 66 },{ 'b', 98 },
{ 'C', 67 },{ 'c', 99 },
{ 'D', 68 },{ 'd', 100 },
{ 'Z', 90 },{ 'z', 122 },
{ '1', 49 },{ '9', 57 },

};
}

@Test(dataProvider = "ValidDataProvider")
public void CharToASCIITest(final char character, final int ascii) {
int result = CharUtils.CharToASCII(character);
Assert.assertEquals(result, ascii);
}

@Test(dataProvider = "ValidDataProvider")
public void ASCIIToCharTest(final char character, final int ascii) {
char result = CharUtils.ASCIIToChar(ascii);
Assert.assertEquals(result, character);
}
}
Result
PASSED: CharToASCIITest(A, 65)
PASSED: CharToASCIITest(a, 97)
PASSED: CharToASCIITest(B, 66)
PASSED: CharToASCIITest(b, 98)
PASSED: CharToASCIITest(C, 67)
PASSED: CharToASCIITest(c, 99)
PASSED: CharToASCIITest(D, 68)
PASSED: CharToASCIITest(d, 100)
PASSED: CharToASCIITest(Z, 90)
PASSED: CharToASCIITest(z, 122)
PASSED: CharToASCIITest(1, 49)
PASSED: CharToASCIITest(9, 57)
PASSED: ASCIIToCharTest(A, 65)
PASSED: ASCIIToCharTest(a, 97)
PASSED: ASCIIToCharTest(B, 66)
PASSED: ASCIIToCharTest(b, 98)
PASSED: ASCIIToCharTest(C, 67)
PASSED: ASCIIToCharTest(c, 99)
PASSED: ASCIIToCharTest(D, 68)
PASSED: ASCIIToCharTest(d, 100)
PASSED: ASCIIToCharTest(Z, 90)
PASSED: ASCIIToCharTest(z, 122)
PASSED: ASCIIToCharTest(1, 49)
PASSED: ASCIIToCharTest(9, 57)

===============================================
com.mkyong.common.CharUtilsTest
Tests run: 24, Failures: 0, Skips: 0
===============================================


===============================================
mkyong
Total tests run: 24, Failures: 0, Skips: 0
===============================================



TestNG Tutorial 7 Dependency Test
Published: May 16, 2009 , Updated: April 1, 2010 , Author: mkyong
print
The Dependency Test means methods are test base on dependency. If the dependent
method fails, all the subsequent test methods will be skipped, not marked as failed.
TestNG uses dependOnMethods to implement the dependency testing as following
import org.testng.annotations.*;

/**
* TestNG Dependency Test
* @author mkyong
*
*/
public class TestNGTest7 {

@Test
public void method1() {
System.out.println("This is method 1");
}

@Test(dependsOnMethods={"method1"})
public void method2() {
System.out.println("This is method 2");
}


}
Result
PASSED: method1
PASSED: method2
The method2() will execute only if method1() is run successfully, else method2()
will skip.


Selenium Framework - Self Created
Q: What is your framework?
Ans :
I am using Hybrid Framework.
Framework contains Application specific components and application independent
components.
Application independent components are like
o Various actions on webpage :
Click
Getattribute
Gettext
Elementpresent
Elementvisible
Waitforelementtopresent
Getvalue
Getselectedoption from List
Switchwindow
Movemouseon
Radiobutton selection
Selectbyvalue
Textbox
Textboxpresent
o Basically to deal with Links, textboxes, List, verifytext, closepopup, database
connection, common database queries to fetch test data



Note : browserpagefactory : Singleton : http://www.javaworld.com/javaworld/jw-04-
2003/jw-0425-designpatterns.html

Q : How does your testdata managed in your framework ?
Ans : We are using Spring Framework for managing testdata.
The lowest level implementation of the IoC container is the BeanFactory, but it is
recommended to use an ApplicationContext for your application. The
ApplicationContext is a subclass of the BeanFactory interface so it has all the
functionality a BeanFactory has and more. Unless you are writing an application that
needs an extremely small memory footprint, BeanFactory shouldn't be used directly.
There are a few different ApplicationContext implementations that can be used, which
can be learned about by reading the Spring Framework's documentation and source
code. For the purposes of this example, we'll use a very popular one
ClassPathXmlApplicationContext, which defaults to reading resources from the
classpath. If you need to use a different location for your classes, you can append
prefixes before the configuration file's path such as 'file', 'http', etc. This will force the
ApplicationContext to read from somewhere other than the default location.
private static ApplicationContext applicationContext = new
ClassPathXmlApplicationContext(getLocations());

private static String[] getLocations() {
if (System.getProperty("app.env") == null) {
System.err.println("[WARNING] No APPLICATION ENVIRONMENT SET in
'app.env'. Using 'default'");
System.setProperty("app.env", "default");
}
return new String[] {
"/applicationContext-storetest.test.xml"
};
}
// The common properties bean
private static CommonPropertiesBean cp = (CommonPropertiesBean)
applicationContext.getBean("commonProperties");


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<!--
This bean points spring to the config file, change value to point to a
new config file
-->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="test.${app.env}.properties" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>

<!--
This bean is the datasource bean, this is what you will use to inject
the Database object
-->
<bean id="storeTestDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

<bean id="storeLocatorTestDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${sl.jdbc.url}" />
<property name="username" value="${sl.jdbc.username}" />
<property name="password" value="${sl.jdbc.password}" />
</bean>

<bean id="storeLocatorServiceTestDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${storelocator.jdbc.url}" />
<property name="username" value="${storelocator.jdbc.username}" />
<property name="password" value="${storelocator.jdbc.password}" />
</bean>

<bean id="jdaTestDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jda.jdbc.driverClassName}" />
<property name="url" value="${jda.jdbc.url}" />
<property name="username" value="${jda.jdbc.username}" />
<property name="password" value="${jda.jdbc.password}" />
</bean>

<bean id="PaypalPropertiesBean"
class="com.gsicommerce.webstore.utilities.PaypalPropertiesBean">
<property name="paypalURL" value="${paypal.url}" />
<property name="paypalMainUser" value="${paypal.main.user}" />
<property name="paypalMainPass" value="${paypal.main.pass}" />
<property name="paypalTestUser" value="${paypal.test.user}" />
<property name="paypalTestPass" value="${paypal.test.pass}" />
</bean>

<!--
This bean is the CommonPropertiesBean, it holds the browser
information for webdriver tests
-->
<bean id="commonProperties"
class="com.gsicommerce.webstore.utilities.CommonPropertiesBean">
<property name="storeCode" value="${store.code}" />
<property name="storeLocale" value="${store.locale}" />
<property name="countryCode" value="${store.countryCode}" />
<property name="currencyCode" value="${store.currencyCode}" />
<property name="productUpdate" value="${product.update}" />
<property name="storeEnvironment" value="${store.environment}" />
<property name="browserType" value="${browser.type}" />
<property name="appURL" value="${app.url}" />
<property name="rtURL" value="${rt.url}" />
<property name="cacheURL" value="${cache.url}" />
<property name="remoteBrowserUrl" value="${remote.browser.url}" />
<property name="catmanURL" value="${catman.url}" />
<property name="catmanUsername" value="${catman.username}" ></property>
<property name="catmanPassword" value="${catman.password}" />
<property name="firefoxProfile" value="${firefox.profile}" />
<property name="browserVersion" value="${browser.version}" />
<property name="browserCapture" value="${browser.capture}" />
<property name="remoteToolsUsername" value="${rt.username}" />
<property name="remoteToolsPassword" value="${rt.password}" />
<property name="storeLocatorURL" value="${storeLocator.url}" />
<property name="testUserName" value="${test.user.name}" />
<property name="testUserPassword" value="${test.user.password}" />
<property name="epiphanyURL" value="${epiphany.url}" />
<property name="epiphanyUsername" value="${epiphany.username}" />
<property name="epiphanyPassword" value="${epiphany.password}" />
<property name="jdaSystem" value="${jda.system}" />
<property name="jdaUsername" value="${jda.username}" />
<property name="jdaPassword" value="${jda.password}" />
<property name="storeLocatorServiceClearCacheUrl"
value="${storeLocatorService.clearCache.url}"/>
</bean>
</beans>

----------------------------------------------------------------------------

public static String storeCode = cp.getStoreCode();








Selenium Interview Questions
Q1. What is Selenium?
Ans. Selenium is a set of tools that supports rapid development of test automation
scripts for web
based applications. Selenium testing tools provides a rich set of testing functions
specifically
designed to fulfil needs of testing of a web based application.

Q2. What are the main components of Selenium testing tools?
Ans. Selenium IDE, Selenium RC and Selenium Grid

Q3. What is Selenium IDE?
Ans. Selenium IDE is for building Selenium test cases. It operates as a Mozilla Firefox
add on and
provides an easy to use interface for developing and running individual test cases or
entire test
suites. Selenium-IDE has a recording feature, which will keep account of user actions
as they are
performed and store them as a reusable script to play back.

Q4. What is the use of context menu in Selenium IDE?
Ans. It allows the user to pick from a list of assertions and verifications for the selected
location.

Q5. Can tests recorded using Selenium IDE be run in other browsers?
Ans. Yes. Although Selenium IDE is a Firefox add on, however, tests created in it can
also be run in
other browsers by using Selenium RC (Selenium Remote Control) and specifying the
name of the test
suite in command line.

Q6. What are the advantage and features of Selenium IDE?
Ans. 1. Intelligent field selection will use IDs, names, or XPath as needed
2. It is a record & playback tool and the script format can be written in various
languages including
C#, Java, PERL, Python, PHP, HTML
3. Auto complete for all common Selenium commands
4. Debug and set breakpoints
5. Option to automatically assert the title of every page
6. Support for Selenium user-extensions.js file

Q7. What are the disadvantage of Selenium IDE tool?
Ans. 1. Selenium IDE tool can only be used in Mozilla Firefox browser.
2. It is not playing multiple windows when we record it.

Q8. What is Selenium RC (Remote Control)?
Ans. Selenium RC allows the test automation expert to use a programming language for
maximum
flexibility and extensibility in developing test logic. For example, if the application under
test returns
a result set and the automated test program needs to run tests on each element in the
result set, the
iteration / loop support of programming languages can be used to iterate through the
result set,
calling Selenium commands to run tests on each item.

Selenium RC provides an API and library for each of its supported languages. This
ability to use
Selenium RC with a high level programming language to develop test cases also allows
the automated
testing to be integrated with the projects automated build environment.

Q9. What is Selenium Grid?
Ans. Selenium Grid in the selenium testing suit allows the Selenium RC solution to
scale for test suites
that must be run in multiple environments. Selenium Grid can be used to run multiple
instances of
Selenium RC on various operating system and browser configurations.

Q10. How Selenium Grid works?
Ans. Selenium Grid sent the tests to the hub. Then tests are redirected to an available
Selenium RC,
which launch the browser and run the test. Thus, it allows for running tests in parallel
with the entire
test suite.

Q 11. What you say about the flexibility of Selenium test suite?
Ans. Selenium testing suite is highly flexible. There are multiple ways to add
functionality to Selenium
framework to customize test automation. As compared to other test automation tools, it
is
Seleniums strongest characteristic. Selenium Remote Control support for multiple
programming and
scripting languages allows the test automation engineer to build any logic they need into
their
automated testing and to use a preferred programming or scripting language of ones
choice.
Also, the Selenium testing suite is an open source project where code can be modified
and
enhancements can be submitted for contribution.

Q12. What test can Selenium do?
Ans. Selenium is basically used for the functional testing of web based applications. It
can be used for
testing in the continuous integration environment. It is also useful for agile testing

Q13. What is the cost of Selenium test suite?
Ans. Selenium test suite a set of open source software tool, it is free of cost.

Q14. What browsers are supported by Selenium Remote Control?
Ans. The test automation expert can use Firefox, IE 7/8, Safari and Opera browsers to
run tests in
Selenium Remote Control.

Q15. What programming languages can you use in Selenium RC?
Ans. C#, Java, Perl, PHP, Python, Ruby

Q16. What are the advantages and disadvantages of using Selenium as testing tool?
Ans. Advantages: Free, Simple and powerful DOM (document object model) level
testing, can be used
for continuous integration; great fit with Agile projects.

Disadvantages: Tricky setup; dreary errors diagnosis; can not test client server
applications.

Q17. What is difference between QTP and Selenium?
Ans. Only web applications can be testing using Selenium testing suite. However, QTP
can be used for
testing client server applications. Selenium supports following web browsers: Internet
Explorer,
Firefox, Safari, Opera or Konqueror on Windows, Mac OS X and Linux. However, QTP
is limited to
Internet Explorer on Windows.

QTP uses scripting language implemented on top of VB Script. However, Selenium test
suite has the
flexibility to use many languages like Java, .Net, Perl, PHP, Python, and Ruby.

Q18. What is difference between Borland Silk test and Selenium?
Ans. Selenium is completely free test automation tool, while Silk Test is not. Only web
applications
can be testing using Selenium testing suite. However, Silk Test can be used for testing
client server
applications. Selenium supports following web browsers: Internet Explorer, Firefox,
Safari, Opera or
Konqueror on Windows, Mac OS X and Linux. However, Silk Test is limited to Internet
Explorer and
Firefox.

Silk Test uses 4Test scripting language. However, Selenium test suite has the flexibility
to use many
languages like Java, .Net, Perl, PHP, Python, and Ruby.

What is Selenium?
Selenium is a suite of tools for browser automation. It is composed of "IDE", a recording
and playback mechanism, "WebDriver" and "RC" which provide APIs for browser
automation in a wide variety of languages, and "Grid", which allows many tests using
the APIs to be run in parallel. It works with most browsers, including Firefox from 3.0 up
to 7, Internet Explorer 8, Google Chrome, Safari and Opera 11.5
Describe technical problems that you had with Selenium tool?
As with any other type of test automation tools like SilkTest, HP QTP, Watir, Canoo
Webtest, Selenium allows to record, edit, and debug tests cases. However there are
several problems that seriously affect maintainability of recorded test cases,
occasionally Quality Assurance Engineers complain that it takes more time to maintain
automated test cases than to perform manual testing; however this is an issue with all
automated testing tools and most likely related to improper testing framework design.
Another problem is complex ID for an HTML element. If IDs is auto-generated, the
recorder test cases may fail during playback. The work around is to use XPath to find
required HTML element. Selenium supports AJAX without problems, but QA Tester
should be aware that Selenium does not know when AJAX action is completed, so
ClickAndWait will not work. Instead QA tester could use pause, but the snowballing
effect of several 'pause' commands would really slow down total testing time of test
cases. The best solution would be to use waitForElement.
What test can Selenium do?
Selenium could be used for the functional, regression, load testing of the web based
applications. The automation tool could be implemented for post release validation with
continuous integration tools like Jenkins, Hudson, QuickBuild or CruiseControl.
What is the price of Selenium license per server?
Selenium is open source software, released under the Apache 2.0 license and can be
downloaded and used without charge.
How much does Selenium license cost per client machine?
Selenium is open source software, released under the Apache 2.0 license and can be
downloaded and used without charge.
Where to download Selenium?
Selenium can be downloaded and installed for free from seleniumhq.org
What is the latest version of Selenium components?
The latest versions are Selenium IDE 1.3.0, Selenium Server (formerly the Selenium
RC Server) 2.9.0, Selenium Client Drivers Java 2.9.0, Selenium Client Drivers C# 2.9.0,
Selenium Client Drivers Ruby 2.8.0, Selenium Client Drivers Python 2.9, Selenium Grid
1.0.8.
What is Selenium IDE?
Selenium IDE is a Firefox add-on that records clicks, typing, and other actions to make
a test cases, which QA Tester can play back in the Firefox browser or export to
Selenium RC. Selenium IDE has the following features: record/play feature, debugging
with step-by-step and breakpoints, page abstraction functionality, an extensibility
capability allowing the use of add-ons or user extensions that expand the functionality of
Selenium IDE


What are the limitations of Selenium IDE?
Selenium IDE has many great features and is a fruitful and well-organized test
automation tool for developing test cases, in the same time Selenium IDE is missing
certain vital features of a testing tool: conditional statements, loops, logging
functionality, exception handling, reporting functionality, database testing, re-execution
of failed tests and screenshots taking capability. Selenium IDE doesn't for IE, Safari and
Opera browsers.
What does SIDE stand for?
Selenium IDE. It was a very tricky interview question.
What is Selenium Remote Control (RC) tool?
Selenium Remote Control (RC) is the powerful solution for test cases that need more
than simple browser actions and linear execution. Selenium-RC allows the developing
of complex test scenarios like reading and writing files, querying a database, and
emailing test reports. These tasks can be achieved by tweaking test cases in your
preferred programming language.
What are the advantages using Selenium as testing tool?
If QA Tester would compare Selenium with HP QTP or Micro Focus SilkTest, QA
Engineer would easily notice tremendous cost savings for Selenium. In contrast to
expensive SilkTest license or QTP license, Selenium automation tool is absolutely free.
It means that with almost no investment in purchasing tools, QA Team could easily build
the state of the art test automation infrastructure. Selenium allows developing and
executing test cases in various programming languages including .NET, Java, Perl,
RubyPython, PHP and even HTML. This is a great Selenium advantage, most likely
your software developers already know how to develop and maintain C# or Java code,
so they transfer coding techniques and best practices to QA team. Selenium allows
simple and powerful DOM-level testing and in the same time could be used for testing in
the traditional waterfall or modern Agile environments. Selenium would be definitely a
great fit for the continuous integration tools Jenkins, Hudson, CruiseControl, because it
could be installed on the server testing box, and controlled remotely from continuous
integration build.

What is Selenium Grid?
Selenium Grid extends Selenium RC to distribute your tests across multiple servers,
saving you time by running tests in parallel.
What is Selenium WebDriver?
Selenium WebDriver is a tool for writing automated tests of websites. It is an API name
and aims to mimic the behaviour of a real user, and as such interacts with the HTML of
the application. Selenium WebDriver is the successor of Selenium Remote Control
which has been officially deprecated.
How many browsers are supported by Selenium IDE?
Test Engineer can record and playback test with Selenium IDE in Firefox.
Can Selenium test an application on iPhone's Mobile Safari browser?
Selenium should be able to handle Mobile Safari browser. There is experimental
Selenium IPhone Driver for running tests on Mobile Safari on the iPhone, iPad and iPod
Touch.
Can Selenium test an application on Android browser?
Selenium should be able to handle Android browser. There is experimental Selenium
Android Driver for running tests in Android browser.
What are the disadvantages of using Selenium as testing tool?
Selenium weak points are tricky setup; dreary errors diagnosis; tests only web
applications
How many browsers are supported by Selenium Remote Control?
QA Engineer can use Firefox 7, IE 8, Safari 5 and Opera 11.5 browsers to run actuall
tests in Selenium RC.
How many programming languages can you use in Selenium RC?
Several programming languages are supported by Selenium Remote Control - C# Java
Perl PHP Python Ruby
How many testing framework can QA Tester use in Selenium RC?
Testing frameworks aren't required, but they can be helpful if QA Tester wants to
automate test cases. Selenium RC supports Bromine, JUnit, NUnit, RSpec (Ruby),
Test::Unit (Ruby), TestNG (Java), unittest (Python).
How to developer Selenium Test Cases?
Using the Selenium IDE, QA Tester can record a test to comprehend the syntax of
Selenium IDE commands, or to check the basic syntax for a specific type of user
interface. Keep in mind that Selenium IDE recorder is not clever as QA Testers want it
to be. Quality assurance team should never consider Selenium IDE as a "record, save,
and run it" tool, all the time anticipate reworking a recorded test cases to make them
maintainable in the future.
What programming language is best for writing Selenium tests?
The web applications may be written in Java, Ruby, PHP, Python or any other web
framework. There are certain advantages for using the same language for writing test
cases as application under test. For example, if the team already have the experience
with Java, QA Tester could always get the piece of advice while mastering Selenium
test cases in Java. Sometimes it is better to choose simpler programming language that
will ultimately deliver better success. In this case QA testers can adopt easier
programming languages, for example Ruby, much faster comparing with Java, and can
become become experts as soon as possible.
Have you read any good books on Selenium?
There are several great books covering Selenium automation tool, you could check the
review at Best Selenium Books: Top Recommended page
Do you know any alternative test automation tools for Selenium?
Selenium appears to be the mainstream open source tool for browser side testing, but
there are many alternatives. Canoo Webtest is a great Selenium alternative and it is
probably the fastest automation tool. Another Selenium alternative is Watir, but in order
to use Watir QA Tester has to learn Ruby. One more alternative to Selenium is Sahi, but
is has confusing interface and small developers community.
Compare HP QTP vs Selenium?
When QA team considers acquiring test automation to assist in testing, one of the most
critical decisions is what technologies or tools to use to automate the testing. The most
obvious approach will be to look to the software market and evaluate a few test
automation tools. Read Selenium vs QTP comparison
Compare Borland Silktest vs Selenium?
Check Selenium vs SilkTest comparison
How to test Ajax application with Selenium
Ajax interview questions could be tough for newbie in the test automation, but will be
easily cracked by Selenium Tester with a relevant experience. Read the detailed
approach at Testing Ajax applications with Selenium in the right way
How can I learn to automate testing using Selenium?
Don't be surprised if the interviewer asks you to describe the approach for learning
Selenium. This interviewer wants to hear how you can innovative software test
automation process the company. Most likely they are looking for software professional
with a good Selenium experience, who can do Selenium training for team members and
get the team started with test automation. I hope this Selenium tutorial will be helpful in
the preparation for this Selenium interview question.
1. What do you know about Selenium?

Selenium is a suite of tools for web automation testing.
Selenium first came to life in 2004 when Jason Huggins was testing an internal
application at ThoughtWorks.
Selenium was a tremendous tool, it wasnt without its drawbacks. Because of its
Javascript based automation engine and the security limitations browsers apply to
Javascript, different things became impossible to do.
Selenium Suite of projects include:
Selenium IDE
Selenium Core
Selenium 1 (known as. Selenium RC or Remote Control)
Selenium 2 (known as. Selenium Webdriver)
Selenium-Grid

2. What are the technical challenges with selenium?
View
As you know Selenium is a free ware open source testing tool. There are many
challenges with Selenium.
1. Selenium Supports only web based applications
2. It doesnt support any non web based (Like Win 32, Java Applet, Java Swing, .Net
Client Server etc) applications
3. When you compare selenium with QTP, Silk Test, Test Partner and RFT, there are
many challenges in terms of maintainability of the test cases
4. Since Selenium is a freeware tool, there is no direct support if one is in trouble with
the support of applications
5. There is no object repository concept in Selenium, so maintainability of the objects is
very high
6. There are many challenges if one have to interact with Win 32 windows even when
you are working with Web based applications
7. Bitmap comparison is not supported by Selenium
8. Any reporting related capabilities, you need to depend on third party tools
9. You need to learn any one of the native language like (.Net, Java, Perl, Python, PHP,
Ruby) to work efficiently with the scripting side of selenium

3. What are the test types supported by Selenium?
Selenium could be used for testing the web based applications. The test types can be
supported are:
1. functional,
2. regression,
3. load testing
The automation tool could be implemented for post release validation with continuous
integration tools like:
1. Jenkins,
2. Hudson,
3. QuickBuild
4. CruiseCont

4. What are the capabilities of Selenium IDE?
Selenium IDE (Integrated Development Environment) works similar to commercial tools
like QTP, Silk Test and Test Partner etc. The below mentioned points describes well
about Selenium IDE.
1. Selenium IDE is a Firefox add-on.
2. Selenium IDE can support recording the clicks, typing, and other actions to make a
test cases.
3. Using Selenium IDE A Tester can play back the test cases in the Firefox browser
4. Selenium IDE supports exporting the test cases and suites to Selenium RC.
5. Debugging of the test cases with step-by-step can be done
6. breakpoint insertion is possible
7. Page abstraction functionality is supported by Selenium IDE
8. Selenium IDE can supports an extensibility capability allowing the use of add-ons or
user extensions that expand the functionality of Selenium IDE
4. What are the capabilities of Selenium IDE?
Selenium IDE (Integrated Development Environment) works similar to commercial tools
like QTP, Silk Test and Test Partner etc. The below mentioned points describes well
about Selenium IDE.
1. Selenium IDE is a Firefox add-on.
2. Selenium IDE can support recording the clicks, typing, and other actions to make a
test cases.
3. Using Selenium IDE A Tester can play back the test cases in the Firefox browser
4. Selenium IDE supports exporting the test cases and suites to Selenium RC.
5. Debugging of the test cases with step-by-step can be done
6. breakpoint insertion is possible
7. Page abstraction functionality is supported by Selenium IDE
8. Selenium IDE can supports an extensibility capability allowing the use of add-ons or
user extensions that expand the functionality of Selenium IDE
6. Which are the browsers supported by Selenium IDE?
Selenium IDE supports only one browser Mozilla Firefox. The versions supported as of
now are:
Mozilla Firefox 2.x
Mozilla Firefox 3.x
The versions not supported as of now are:
earlier versions of Mozilla Firefox 2.x
Mozilla Firefox 4.x
7. How to execute a single line command from Selenium IDE?
Single line command from Selenium IDE can be executed in two ways
1. Right click on the command in Selenium IDE and select "Execute This Command"
2. Select the command in Selenium IDE and press "X" key on the keyboard
8. How to insert a start point in Selenium IDE?
Start point Selenium IDE can be set in two ways
1. Right click on the command in Selenium IDE and select "Set / Clear Start Point"
2. Select the command in Selenium IDE and press "S" key on the keyboard
3. You can have only one start point
4. If you have already set one start point and you selected other command as start
point. Then the first start point will be removed and the new start point will be set
1. Right click on the command in Selenium IDE and select "Inert New Comment"
2. If you want to comment an existing line. You need to follow the below mentioned
steps.
a. Select the source tab in IDE
b. Select the line which you want to comment
c. Assume that if you want to comment a open command you need to write like below
mentioned code
<tr>
<!--
<td>open&l/td>
<td>/node/304/edit&l/td>
<td></td>
-->
</tr>

9. How to insert a comment in Selenium IDE?
Comments in Selenium IDE can be set in two ways
1. Right click on the command in Selenium IDE and select "Inert New Comment"
2. If you want to comment an existing line. You need to follow the below mentioned
steps.
a. Select the source tab in IDE
b. Select the line which you want to comment
c. Assume that if you want to comment a open command you need to write like below
mentioned code
<tr>
<!--
<td>open&l/td>
<td>/node/304/edit&l/td>
<td></td>
-->
</tr>

10. How to insert a break point in Selenium IDE?
Break point can be set in two ways in Selenium IDE
1. Right click on the command in Selenium IDE and select "Toggle Break Point"
2. Select the command in Selenium IDE and press "B" key on the keyboard
3. If you want to clear the break point once again Spress "B" key on the keyboard
4. You can set multiple break points in Selenium IDE
11. How to debug the tests in Selenium IDE?
To debug or execute the test cases line by line. Follow the below mentioned steps
1. Insert a break point (see the question to know more How to insert a break point in
Selenium IDE? )from the location where you want to execute step by step
2. Run the test case
3. execution will be paused at the given break point
4. Click on the step (Blue) button to continue with the next statement
5. Click on Run button, to continue executing all the commands at a time
12. How to export the tests from Selenium IDE to Selenium RC in different languages?
From selenium IDE the test cases can be exported into the languages
1. .Net,
2. Java,
3. Perl,
4. Python,
5. PHP,
6. Ruby
The below mentioned steps can explain how to export the test cases
1. Open the test case from Selenium IDE
2. Select File -> Export Test Case As
13. How to export Selenium IDE Test Suite to Selenium RC Suites?
From selenium IDE the test suites can be exported into the languages as mentioned
below
1. .Net,
2. Java,
3. Perl,
4. Python,
5. PHP,
6. Ruby
The below mentioned steps can explain how to export the test suites
1. Open the test case from Selenium IDE
2. Select File -> Export Test Suite As
14. Which is the command used for displaying the values of a variable into the output
console or log?
The command used for displaying the values of a variable into the output console or log
- echo
If you want to display a constant string. The below mentioned command can be used
echo <constant string>
ex: echo "The sample message"
If you want to display the value of a variable it can be written like below
echo ${<variable name>>
ex: echo ${var1}
Note: Here var1 is the variable
15. Which are the browsers supported by Selenium RC?
Supported browsers for Selenium RC include:
1. *firefox
2. *mock
3. *firefoxproxy
4. *pifirefox
5. *chrome
6. *iexploreproxy
7. *iexplore
8. *firefox3
9. *safariproxy
10. *googlechrome
11. *konqueror
12. *firefox2
13. *safari
14. *piiexplore
15. *firefoxchrome
16. *opera
17. *iehta
18. *custom
Note: Any third party browser is supported with *custom followed by the complete path
of the browser with executable
16. Which are the Operating Systems supported by Selenium?
Selenium IDE
Works in Firefox 2+ Start browser, run tests Run tests
Operating Systems Supported:
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others whichever supports Firefox 2+
Selenium Remote Control
Used for starting browser and run tests
Operating Systems Supported:
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others
Selenium Core
Used for running tests
Operating Systems Supported:
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others
17. What is Selenium RC?
View
Selenium-RC is the solution for tests that need a little more than just simple browser
actions and a linear execution. Selenium-RC leverages the full power of programming
languages, creating tests that can do things like read and write external files, make
queries to a database, send emails with test reports, and practically anything else a
user can do with a normal application.
You will want to use Selenium-RC whenever your test requires logic not supported by
running a script from Selenium-IDE

18. Why Selenium RC is used?
Selenium-IDE does not directly support:
1. condition statements
2. iteration
3. logging and reporting of test results
4. error handling, particularly unexpected errors
5. database testing
6. test case grouping
7. re-execution of failed tests
8. test case dependency
9. capture screenshots on test failures
The reason behind why Selenium-IDE does not support the above mentioned
requirements is IDE supports only HTML language. Using HTML language we cannot
achieve the above mentioned requirements. Because HTML does not support
conditional, looping and external source connectives.
To overcome the above mentioned problems Selenium RC is used.
Since Selenium RC supports the languages .Net, Java, Perl, Python, PHP, and Ruby. In
these languages we can write the programme to achieve the IDE issues


19. Which are the languages supported by Selenium RC?
View
The languages supported by Selenium RC
1. .Net,
2. Java (Junt 3, Junt 4, TestNG, Groovy)
3. Perl,
4. Python,
5. PHP,
6. Ruby
20. What is Selenium Grid?
View
Selenium Grid is part of Selenium suite of projects. Selenium Grid transparently
distribute your tests on multiple machines so that you can run your tests in parallel,
cutting down the time required for running in-browser test suites. This will dramatically
speeds up in-browser web testing, giving you quick and accurate feedback you can rely
on to improve your web application.

21. What is Selenium WebDriver or Google WebDriver or Selenium 2.0?
View
WebDriver uses a different underlying framework from Seleniums javascript Selenium-
Core. It also provides an alternative API with functionality not supported in Selenium-
RC. WebDriver does not depend on a javascript core embedded within the browser,
therefore it is able to avoid some long-running Selenium limitations.
WebDrivers goal is to provide an API that establishes
A well-designed standard programming interface for web-app testing.
Improved consistency between browsers.
Additional functionality addressing testing problems not well-supported in Selenium
1.0.
The Selenium developers strive to continuously improve Selenium. Integrating
WebDriver is another step in that process. The developers of Selenium and of
WebDriver felt they could make significant gains for the Open Source testautomation
community be combining forces and merging their ideas and technologies. Integrating
WebDriver intoSelenium is the current result of those efforts.

22. What are the capabilities of Selenium WebDriver or Google WebDriver or Selenium
2.0?
One should use WebDriver when requiring improved support for
Mult-browser testing including improved functionality for browsers not well-supported
by Selenium-1.0.
Handling multiple frames, multiple browser windows, popups, and alerts.
Page navigation.
Drag-and-drop.
AJAX-based UI elements.
nderlying framework from Seleniums javascript Selenium-Core. It also provides an
alternative API with functionality not supported in Selenium-RC. WebDriver does not
depend on a javascript core embedded within the browser, therefore it is able to avoid
some long-running Selenium limitations.
WebDrivers goal is to provide an API that establishes
A well-designed standard programming interface for web-app testing.
Improved consistency between browsers.
Additional functionality addressing testing problems not well-supported in Selenium
1.0.
The Selenium developers strive to continuously improve Selenium. Integrating
WebDriver is another step in that process. The developers of Selenium and of
WebDriver felt they could make significant gains for the Open Source testautomation
community be combining forces and merging their ideas and technologies. Integrating
WebDriver intoSelenium is the current result of those efforts.
24. What is the architecture of Selenium Grid?
The below mentioned theory explains about the setup of Selenium Grid with
architecture and how it works.
Selenium Grid builds on the traditional Selenium setup, taking advantage of the
following properties:
* The Selenium test, the application under test, and the remote control/browser pair do
not have to be co-located. They communicate through HTTP, so they can all live on
different machines.
* The Selenium tests and the web application under test are obviously specific to a
particular project. Nevertheless, neither the Selenium remote control nor the browser is
tied to a specific application. As a matter of fact, they provide a capacity that can easily
be shared by multiple applications and multiple projects.
Consequently, if only we could build a distributed grid of Selenium Remote Controls, we
could easily share it across builds, applications, projects - even potentially across
organizations. Of course we would also need to address the scalability issues as
described earlier when covering the traditional Selenium setup. This is why we need a
component in charge of:
* Allocating a Selenium Remote Control to a specific test (transparently)
* Limiting the number of concurrent test runs on each Remote Control
* Shielding the tests from the actual grid infrastructure
Selenium Grid calls this component the Selenium Hub.
* The Hub exposes an external interface that is exactly the same as the one of a
traditional Remote Control. This means that a test suite can transparently target a
regular Remote Control or a Selenium Hub with no code change. It just needs to target
a different IP address. This is important as it shields the tests from the gridinfrastructure
(which you can scale transparently). This also makes the developers life easier. The
same test can be run locally on a developer machine, or run on a heavy duty distributed
grid as part of a build without ever changing a line of code.
* The Hub allocates Selenium Remote Controls to each test. The Hub is also in charge
of routing the Selenese requests from the tests to the appropriate Remote Control as
well as keeping track of testing sessions.
* When a new test starts, the Hub puts its first request on hold if there is no available
Remote Control in the grid providing the appropriate capabilities. As soon as a suitable
Remote Control becomes available, the Hub will serve the request. For the whole time,
the tests do not have to be aware of what is happening within the grid; it is just waiting
for an HTTP response to come back.
25. Does Selenium support mobile internet testing?
View
Selenium supports Opera. And opera is used in most of the Smart phones. So
whichever Smart phone supports opera, selenium can be used to test. So, one can use
Selenium RC to run the tests on mobiles.
For more details on supported browsers of Selenium Which are the browsers supported
by Selenium RC?
26. Does Selenium support Google Android Operating System?
View
Yes, Selenium Web Driver or Google Web Driver or Selenium 2.0 supports Android
Operating System. There are several libraries written to support Android Operating
System.
Fri, 07/15/2011 - 04:35 Visitor
selenium android driver testing
try this .... this is cool ... ;)
public class OneTest extends TestCase {
public void testGoogle() throws Exception {
AndroidDriver driver = new AndroidDriver();
// And now use this to visit Google
driver.get("http://google.com");
Thread.sleep(15000);
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("hotmail");
//driver.findElement(By.name("q")).sendKeys("niloy.cit");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
//driver.findElement(By.name("btnG")).click();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}

how i can give command to a already run webdriver to open an application or websight
in emulator or real device ??


27. What are the types of text patterns available in Selenium?
There are three types of patterns available in Selenium
1. globbing
2. regular expressions
3. exact
28. How to use regular expressions in Selenium?
Regular expressions in Selenium IDE can be used with the keyword - regexp: as a
prefix to the value and patterns needs to be included for the expected values.
For example if you want to use the regular expression for a command
Command: verifyText
Target: //font/font/b/font[1]
Value: Flight Confirmation # 2011-05-02451
in the above example Flight Confirmation is continuously changing each time you run
the test case. So this can be written with a regular expression as mentioned below
Command: verifyText
Target: //font/font/b/font[1]
Value: regexp:Flight Confirmation # [0-9]{4}-[0-9]{2}-[0-9]{5,10}
29. What are the regular expression patterns available in Selenium?
Selenium regular expression patterns offer the same wide array of special characters
that exist in JavaScript. Below are a subset of those special characters
PATTERN MATCH
. any single character
[ ] character class: any single character that appears inside the brackets
* quantifier: 0 or more of the preceding character (or group)
+ quantifier: 1 or more of the preceding character (or group)
? quantifier: 0 or 1 of the preceding character (or group)
{1,5} quantifier: 1 through 5 of the preceding character (or group)
| alternation: the character/group on the left or the character/group on the right
( ) grouping: often used with alternation and/or quantifier


30. What is Selenese?
Selenium set of commands which are used for running the test are called as Selenese.
There are three types of Selenese, those are:
1. Actions - used for performing the operations and interactions with the target elements
2. Assertions - used as check points
3. Accessors - used for storing the values in a variable

31. How do you add check points or verification points in Selenium?
check points or verification points are known as Assertions in Selenium. The keywords
with below mentioned prefix will be used for adding check points or verification points.
1. verify
2. assert
3. waitFor
32. What is Assertion in Selenium?
Assertion is nothing but a check or verification point.
Assertion verifies the state of the application conforms to what is expected.
Examples include make sure the page title is X and verify that this checkbox is
checked.
33. What are the types of Assertions there in Selenium?
Selenium Assertions can be used in 3 modes:
1) assert - When an assert fails, the test will be aborted. If you are executing test suite,
the next state case will start
2) verify - When a verify fails, the test will continue execution, logging the failure.
3) waitFor - waitFor commands wait for some condition to become true (which can be
useful for testing Ajaxapplications). They will succeed immediately if the condition is
already true. However, they will fail and halt the test if the condition does not become
true within the current timeout setting


34. When to use Assert, Verify and WaitFor in Selenium?
1) assert - If the expected value is mandatory to continue with the next set of steps we
will use Assert. As Assert aborts the test, if the expected value doesn't match. It is good
to use for any mandatory checks.
2) verify - If the expected value is optional to continue with the next set of steps we will
use Verify. As Verify continues executing with the next set of steps, if the expected
value doesn't match. It is good to use for any optional checks.
3) waitFor - If your test needs to wait, if the expected value is not matching we use
waitFor. We normally use waitFor for AJAX kind of controls loading within a page


35. What is an Accessor in Selenium?
Accessor is one of the type of Selenese.
I. Accessors are used for storing the value of a target in a variable.
Ex:
1) storeTitle - Stores the title of a window in a variable
2) storeText - Stores the target element text in a variable
II. Accessors are also used for evaluating the result and storing the result in a variable
Ex: storeTextPresent - Evaluates whether the text is present in the current window. If
the text is present stores true in the variable else stores false
Ex: storeEementPresent - Evaluates whether the element is present in the current
window. If the element is present stores true in the variable else stores false
36. When to use Accessors in Selenium?
View
Accessors are mostly used for storing the value in a variable.
The variable can be used for following reasons:
1) To get the value from an element and comparing with some dynamic value
2) To take a logical decision to execute the test steps
ex: if the value of the variable true execute step1 and step2 else step3 and step4
3) To execute some statements in a loop based on the value returned by the element
37. How to capture bitmaps in Selenium?
View
Bitmaps are captured using the Selenium set of commands. There are two modes of
capturing the bitmaps
1) Capture the bitmap for the entire page - it captures the browser main page area of
AUT
2) Capture the bitmap for the screen shots - it captures the entire screen shot like the
print scree that you give from your keyboard
Selenium doesn't support bitmap capturing for an element on AUT.
38. Which are the commands used for capturing the bitmaps?
captureEntirePageScreenshot
Saves the entire contents of the current window canvas to a PNG file. Contrast this with
the captureScreenshot command, which captures the contents of the OS viewport (i.e.
whatever is currently being displayed on the monitor), and is implemented in the RC
only. Currently this only works in Firefox when running in chrome mode, and in IE non-
HTA using the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly
borrowed from the Screengrab! Firefox extension. Please see
captureEntirePageScreenshot for more details
captureEntirePageScreenshotAndWait
Saves the entire contents of the current window canvas to a PNG file. Contrast this with
the captureScreenshot command, which captures the contents of the OS viewport (i.e.
whatever is currently being displayed on the monitor), and is implemented in the RC
only. Currently this only works in Firefox when running in chrome mode, and in IE non-
HTA using the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly
borrowed from the Screengrab! Firefox extension. Please see
captureEntirePageScreenshotAndWait for details.
Note: This command runs with only mozilla firefox when you run the tests from RC.
Other browsers it will not support
39. What is the difference between captureEntirePageScreenshot and
CaptureScreenShot?
View
captureEntirePageScreenshot
1. This captures the AUT web page only
2. This supports only mozilla firefox
3. Accepts two arguments. one is the file name to be saved and other argument is back
ground color
CaptureScreenShot
1. This captures the System screen shot
2. This supports all the browsers when you run from Selenium RC
3. Accepts one argument. That is the file name to be saved.


41. What are the limitations of Selenium IDE
View
The limitations of Selenium IDE are:
1) Selenium IDE uses only HTML language
2) Conditional or branching statements execution like using of if, select statements is
not possible
3) Looping statements using is not possible directly in Selenium HTML language in ide
4) Reading from external files like .txt, .xls is not possible
5) Reading from the external databases is not possible with ide
6) Exceptional handling is not there
7) A neat formatted Reporting is not possible with ide
To eliminate the above issues we use Selenium RC


Selenium Framework - Process
Designing Test Automation Framework with Selenium
by seetaram on June 19, 2011
Do we need to go for Test Automation? If yes, then which is the tool? If we straight
away start automating test cases what are all the technical challenges we might face?
Do we need a framework for Automation? How we go about designing a framework?
These are all the questions popup when we want to start Test Automation. Okay, let us
start exploring answers for the above questions.
If there are hundreds of test scenarios which needs to be executed on each build then it
will be a tedious task and error prone. Because a Test Engineer might make mistakes
while entering the test data and output might be wrong. We can avoid such situations
by automating the test cases.
Before selecting a tool for Test Automation, we need to analyze the technologies used
for different UI components. For example, Java Swing components, Telerik controls,
ExtJS tables, Ajax, Silverlight, Flex / Flash controls, etc. If we want to use Selenium as
Test Automation tool then the first and foremost thing needs to be checked is whether
the application is a Web Application. If so, then check whether most of the UI controls
are identified by the Selenium. If more than 70% of the test cases can be automated
then definitely we can go ahead and automate the test cases.
In order to handle large number of test cases we need to have a clear cut strategy for
designing the framework. Some of the framework functionalities can be mentioned as
follows:
1. If there is any unhandled exception, then the execution should not stop. Particular
test scenario should be stopped and continue with the next scenario.
2. Screen shots must be taken for each error so that analyzing the failures should be
easy.
3. Proper exception handling should be done in the framework.
4. Proper naming convention should be used
5. Avoid hard coding test data
6. Test Data should be parameterized using external means such as XMLs,
Database, Spreadsheet, etc.
7. Logs should be created that makes life easier while analyzing the Test Execution
8. Proper folder structure should be created.

If we need to create a Test Automation Framework with all the above mentioned
features (or anything beyond this) for Selenium, then we need to use the programming
language as JAVA and Eclipse as the IDE (Integrated Development Environment).
Test Automation Engineers should have knowledge of Java then it makes their life
easier for automating the test cases.
We will discuss further about the framework in the next blog post.


Selenium Testing Framework Pt. 1: Testing Concepts
November 2nd, 2011 by Jason Smiley
This is part 1 of a 3-part guest blog series by Jason Smiley, QA Engineer at Gerson
Lehrman Group.
When writing test scripts, you might find yourself trying to solve similar problems over
and over again. So why not re-use the same solutions over and over again? The
following framework will help you get the most out of your code without needing to do
tons of maintenance every time something changes.
Before getting into specifics, lets first talk about what should be implemented when
writing test scripts. At GLG, our tests typically go through a set of steps on the website.
They also have to interact with elements on the site in order to accomplish these steps.
Then there is the actual tests themselves, which review the displayed content on the
site. Essentially, we have tests that assert the content on the site, a set of steps we
need to take in order to perform these tests (which, for the sake of this blog post, I will
describe as actions), and then the pages with elements that we are checking or
interacting with.
When drawn as an ERD, we have something like this:

How can we best make use of this structure? We want tests to focus on use cases,
actions that focus on what steps to take, and pages that allow us to interact with them.
From a development standpoint, this means we have tests containing a list of actions
that can be used to obtain the values required to check or change the state of the
system under testing. Actions can interact with pages in order to complete these steps
and make sure they accomplished their task. Pages can be used by actions or tests to
add, edit, clear, or read data. Adding these relationships to the ERD, we get something
like this:


What does this look like in code? How would we best accomplish this task? Well, that
depends on what you are doing. For example, maybe you need to test 5 different types
of projects, or maybe you need to test same page differently each time. Either way, as a
coding standard, you should always design classes with a specific purpose. Anything
that is shared should go into a base class for common functionality.
In the next blog post, I will describe how to set up different base classes for tests,
pages, and actions. Then in part three of this blog post series, I will show you how to
bring all of this together for testing your local projects.

Selenium Testing Framework Pt 2: Base Classes
November 17th, 2011 by Jason Smiley
This is part 2 in a 3-part guest blog post series by Jason Smiley, a QA Engineer at
Gerson Lehrman Group.
In my last blog post, I showed what testing as a whole would look like, regardless of
what we actually need to test. Just to recap, we have tests that check and validate
results, actions that are a set of steps to take before having a value we can check, and
pages that can be checked or interacted with.
For the sake of this article, lets assume we will be testing several different websites
with different code bases that are partially related. For example, we will have an admin
site that can add, edit, and remove content from a different public content site.
Assuming we have two different test projects, or one for each site, the first thing we
need to do is create a base test, action, and page class that can be used by either test
project to reduce the amount of code that needs to be written. These can also reduce
any maintenance that needs to be done on updating common functionality.
Later, we can have another set of base classes that extend the shared base classes but
are more specific to the project under test. Since there will be shared code, it is a good
idea to create a separate project that can be referenced in your test projects. This
allows you to change base code sets fairly easily, which can be useful if changing to a
different testing framework.
Selenium Base Test Class
First, well talk about a base test class. All tests need a browser, so first we must write a
function that will create a browser. The tests will need to connect to the DB to allow for
data checking, and it will also need utility functions so you can look at popups or switch
between active frames. Lets create SeleniumTestBase.cs class, which has these
functions. In C#, it will look something like this:
public SeleniumTestBase
{
protected IWebDriver myDriver;

public SeleniumTestBase (IWebDriver webDriver)
{
myDriver = webDriver;
}

public DataTable GetData(string connString, string SQL)
{
//Some code which will query a DB for you
}

public IWebDriver StartBrowser(string browserType)
{
//Some code which will launch different types of browsers
}

public void SwitchToWindow(string handle)
{
//Some code which will switch windows for you
}

public void SwitchToFrame(string handle)
{
//Some code which will switch frames for you
}

public void LaunchUrl(string URL)
{
//Some code which will navigate directly to the specified URL.
}

public void Refresh()
{
//Some code to refresh the page you are currently on
}
}
Now, its important to note here that many of these functions dont seem to be that hard
to implement. In that case, why create a base class to encapsulate standard
functionality already inherent to the Selenium Framework? There are two reasons for
this.
One is that you will have less typing to do, which is always nice. The other is that,
should you decide to change testing frameworks (from say Selenium 1 to Selenium 2),
you will only need to update one class that handles all of the basic interactions. The
ways of doing things may change from one framework release to the next. By
encapsulating your code, you ensure that your code will always work the same as
maintenance is performed since all tests will still call the same functions.
Selenium Action Base Class
Now well move on to actions. Actions will execute the steps that will change the state of
the website being tested (such as being signed in). Actions may also need to revert
changes done by tests to a database for data cleanup, navigate to different pages,
refresh the page, or interact with different frames and windows from the current active
environment. Although the interactions between an action class and a page will be test
specific, we can start writing the ways an action will interact with a browser or DB. A
SeleniumActionBase.cs class will probably look something like this:
public SeleniumActionBase
{
protected IWebDriver myDriver;

public SeleniumActionBase(IWebDriver webDriver)
{
myDriver = webDriver;
}

public DataTable ExecuteSQL(string connString, string SQL = , string SPName = ,
string[] Parameters = new string[] {})
{
//Some code which will execute a query or stored proceedure for you
}

public void SwitchToWindow(string handle)
{
//Some code which will switch windows for you
}

public void SwitchToFrame(string handle)
{
//Some code which will switch frames for you
}

public void LaunchUrl(string URL)
{
//Some code which will navigate directly to the specified URL.
}

public void Refresh()
{
//Some code to refresh the page you are currently on
}
}
There are a couple of things Id like to clarify about the above example when it comes to
updating the database during test scripts:
If you are going to manually execute SQL to clean up your work after a test, you
should be able to do so by using custom SQL or by calling stored procedures directly
(hence the optional parameters). In my experience, it is always better to use a stored
procedure rather than using your own SQL to update a DB to ensure that you arent
creating a data issue.
You might not be able to actually update a DB directly using SQL due to internal
security protocols. Or maybe you wont even be comfortable doing this as your test
code could break the DB. However, executing SQL to clean up your code is going to be
much faster and more dependable than doing it through the UI. Im not saying you
should or should not clean up your tests this way, but if you are going to execute SQL to
clean up your code, Id advocate doing it this way.
Selenium Page Class
The last piece of the puzzle are the actual pages themselves. Pages are essentially just
a grouping of page elements you wish to check and interact with. To code this the most
efficient way, you should break the idea of a page into two separate classes.
One class, which I will refer to as a page class, is specific to the test project in the sense
that it relates to the actual pages you want to test. From a coding perspective, these are
the locator strings. Regardless of what framework you are using, you need to be able to
find your elements. Typically, this is done by Id, XPath, or CSS, and generally wont
change unless the page youre testing changes. Since some locator strings could be
based on the browser start index, and browser start indexes can either be 1 or 0, the
page class will need to know which browser is being used. Based on this, a
SeleniumPageBase.cs class would look something like this:
public SeleniumPageBase
{
protected IWebDriver myWebDriver;

public SeleniumPageBase(IWebDriver webDriver)
{
myWebDriver = webDriver;
}

protected int browserIndex
{
get
{
return /*Code to get Browser index*/;
}
}
}
The second page class will handle the actual interactions between the test or action and
the page. This is usually done by Selenium itself, however, a Selenium object isnt
always easy to use. A lot of times, you have to wait for the DOM to update the element
you want to check, click, or interact with, especially if the page you are testing is using
AJAX or Javascript. If an element fails, you might want to add additional error
messaging to say what caused the interaction to fail. By using a level of encapsulation,
you can better control the use of your Selenium or testing framework code.
Since this class is supposed to handle interactions of specific elements on a page, I will
call this class a SeleniumPageElement. It is important to note that a page element class
will need to mimic what a IWebElement or whatever framework you choose can
do, as our actions and tests will be interacting with this class. By taking the testing
frameworks place, we make it easier to swap out testing frameworks for new ones with
little changes in test code.
Here is an example of what a SeleniumPageElement.cs class would look like:
public SeleneniumPageElement
{
public By myBy;
public IWebDriver myDriver;
public int? myIndex;
public SeleneniumPageElement myParent;

public SeleneniumPageElement(By locator, IWebDriver webDriver,
SeleneniumPageElement parent = null, int? index = null)
{
myBy = locator;
myDriver = webDriver;
myIndex = index;
myParent = parent;
}

public IWebElement GetNow(string errorMessage = )
{
try
{
if(myParent != null)
{
if(myIndex != null)
{
return myParent.GetNow().FindElements(myBy)[MyIndex];
}
return myParent.GetNow().FindElement(myBy);
}

if(myIndex != null)
{
return myDriver.FindElements(myBy)[MyIndex];
}
return myDriver.FindElement(myBy);
}
catch(Exception e)
{
if(errorMessage.Equals(string.Empty) == false)
{
throw new Exception(errorMessage, e);
}
throw e;
}
}
public IWebElement WaitingGet(int seconds = 5, string errorMessage = )
{
//Waiting function using above method.
}

public void Click(int seconds = 5, string errorMessage = )
{
WaitingGet(seconds, errorMessage).Click();
}
In the last post of this series, I will go over how to connect what I covered in posts 1 and
2 and put it all together in your project.
Footnote: You will also need to write other waiting functions as well as interaction
functions * to handle your framework calls. The above functions will handle the structure
of the page element class to allow your other functions to handle specific interactions
such as clicking or other types of waiting such as WaitUntilVisible(int seconds = 5, string
errorMessage = ) or WaitUntilNotVisible(int seconds = 5, string errorMessage = ).
Selenium Testing Framework Part 3: Putting It All Together
December 6th, 2011 by Jason Smiley
This is the final post in a 3-part guest blog series by Jason Smiley, a QA Engineer at
Gerson Lehrman Group. You can read his first post here and his second post here.
If youve been following along with my other posts on building a Selenium testing
framework, you know weve covered some of the high-level testing concepts and base
classes so far. Now that we have defined all our working parts, lets see how we would
pull this above code into our test projects. To summarize specficially what we talked
about in the last blog, we have defined the following classes.
SeleniumTestBase.cs, which handles creating of the test browser, reading from the
DB, and handles changing of active windows or frames.
SeleniumActionBase.cs, which can update the DB and also can handle changing of
the active windows or frames.
SeleniumPageBase.cs, which checks the starting number of the XPath browser
index (IE uses 0 while all other browsers use 1).
SeleniumPageElement.cs, which handles waiting for and interacting with elements
on the page.
Since I mentioned the above classes should be in an external project from your testing
project, I will refer to these set of classes in compiled form as the
OurSeleniumFramework.dll. This .dll file should be referenced in your test project so
test, action, and page classes can extend the base classes we created.
When creating a test project to test a website, it is a good idea to create a project base
test that will create all of our action and page classes, as well as having a project base
action class that will create all our page classes. Page classes will create
SeleniumPageElements, which will be used by action and test classes.
Example Test Project
To demonstrate this structure, I will show how base classes are created and how this
can be used to test a login page which has a username field, password field, submit
button, login confirmation message that appears after successful login, and error
message that appears after unsuccessful attempts. I will now show what each class
required to perform a basic login test will look like. I will also add notes in the tests to
show why something is being done. See below for all the example test project files. The
files will be:
1. ProjectTestBase.cs: Handles NUnit setup, teardown, and page and action
initialization functionality for tests.
2. ProjectActionBase.cs: Handles page initialization functionality for actions.
3. LoginTests.cs: Implements the tests for the login page.
4. LoginActions.cs: Implements the steps required to do Login testing.
5. LoginPage.cs: Handles the initialization for PageElement objects which will be used
by actions and tests.
Example ProjectTestBase.cs
public ProjectTestBase : SeleniumTestBase
{
#region Action declarations
protected LoginActions _LoginActions;
#endregion

#region Page declarations
protected LoginPage _LoginPage;
#endregion

public ProjectTestBase (IWebDriver webDriver)
: base(webDriver) { }

public void CreateActions(IWebDriver webDriver)
{
_LoginActions = new LoginActions(webDriver);
}

public void CreatePages(IWebDriver webDriver)
{
_LoginPage= new LoginPage(webDriver);
}

[SetupTestFixture]
public virtual void setupTestFixture()
{
//Function is virtual so child test classes can have additional functionality.

//For this example project, nothing needs to be done on this level.
}

[Setup]
public virtual void setup()
{
//Function is virtual so child test classes can have additional functionality.
myDriver = StartBrowser(firefox);
CreateActions(myDriver);
CreatePages(myDriver);
LaunchUrl(http://myhomepage.com);
}

[Teardown]
public virtual void tearDown()
{
//Function is virtual so child test classes can have additional functionality.
myDriver.Quit();
}

[TeardownTestFixture]
public virtual void setupTestFixture()
{
//Function is virtual so child test classes can have additional functionality.

//For this example project, nothing needs to be done on this level.
}
}
Example ProjectActionBase.cs
public ProjectActionBase : SeleniumActionBase
{

#region Page declarations
protected LoginPage _LoginPage;
#endregion

public ProjectActionBase(IWebDriver webDriver)
: base(webDriver);
{
_LoginPage = new LoginPage(webDriver);
}
}
(Id like to point out here that in this class, you can put common actions such as
successful login so all action classes will be able to perform this step. This is just a nice-
to-have, though, and not a must.)
Example LoginTests.cs
public LoginTests : ProjectTestBase
{

[Test]
public void successfulLoginTest()
{
_LoginActions.LoginAttempt(Jason, Smiley, true);
Assert.That(_LoginPage.ConfirmationMessage.Text, Is.EqualTo(You are now logged
in).IgnoreCase, You should have logged in successfuly but didnt);
}

[Test]
public void invalidLoginTest()
{
_LoginActions.LoginAttempt(fake, fake, false);
Assert.That(_LoginPage.ErrorMessage.Text, Is.EqualTo(Invalid login).IgnoreCase,
You should have gotten an error message but didnt)
}
}
Example LoginActions.cs
public LoginActions : ProjectActionBase
{
public void LoginAttempt(string username, string password, isValid = null)
{
LoginPage.UsernameTextField.Clear();
LoginPage.UsernameTextField.SendKeys(username);
LoginPage.PasswordTextField.Clear();
LoginPage.PasswordTextField.SendKeys(password);
LoginPage.SubmitBtn.Click();

if(isValid != null && isValid == true)
{
LoginPage.ConfirmationMessage.
WaitUntilVisibleAndPresent(confirmation is not appearing after 5 seconds);
}

if(isValid != null && isValid == false)
{
LoginPage.ErrorMessage.WaitUntilVisibleAndPresent(error message is not appearing
after 5 seconds);
}
}
}
Example LoginPage.cs
public LoginPage : SeleniumPageBase
{
#region PageElement declarations
public PageElement UsernameTextField;
public PageElement PasswordTextField;
public PageElement ConfirmationMessage;
public PageElement ErrorMessage;
#endregion

public LoginPage(IWebDriver webDriver)
: base(webDriver)
{
UsernameTextField = new PageElement(By.Id(username), webDriver);
PasswordTextField= new PageElement(By.Id(password), webDriver);
ConfirmationMessage= new PageElement(By.Id(success), webDriver);
ErrorMessage= new PageElement(By.Id(error), webDriver);
}
}



Java : Collections
Collection Interface

List Interface


The List interface extends Collection

Declares the behavior of a collection that stores a sequence of elements. Elements
can be inserted or accessed by their position in the list, using a zero-based
index. A list may contain duplicate elements.

Set Interface

The Set interface defines a set.

It extends Collection

Declares the behavior of a collection that does not allow duplicate elements.

add( ) method returns false if an attempt is made to add duplicate elements to a set.
It does not define any
additional methods of its own.
SortedSet Interface

SortedSet interface extends Set

Declares the behavior of a set sorted in ascending order.

SortedSet defines several methods that make set processing more convenient. To
obtain the first object in the set, call first( ). To get the last element, use last( ).
You can obtain a subset of a sorted set by calling subSet( ), specifying the first
and last object in the set. If you need the subset that starts with the first element
in the set, use headSet( ). If you want the subset that ends the set, use tailSet( ).


ArrayList Class

Implements the List interface.

ArrayList supports dynamic arrays that can grow as needed. That is, an ArrayList can
dynamically
increase or decrease in size.

// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " +
al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);
}
}

The output from this program is shown here:
Initial size of al: 0
Size of al after additions: 7

Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]


LinkedList Class

Implements the List interface.

It provides a linked-list data structure.

In addition to the methods that it inherits, the LinkedList class defines some useful
methods of its own for manipulating and accessing lists. To add elements to the
start of the list, use addFirst( ); to add elements to the end, use addLast( ). Their
signatures are shown here:
void addFirst(Object obj)
void addLast(Object obj)
HashSet Class

Implements the Set interface.

It creates a collection that uses a hash table for storage.

Hash table stores information by using a mechanism called hashing. In hashing, the
informational content
of a key is used to determine a unique value, called its hash code. The hash code
is then used as the index at which the data associated with the key is stored.
The transformation of the key into its hash code is performed automaticallyyou
never see the hash code itself. Also, your code cant directly index the hash
table.

The advantage of hashing is that it allows the execution time of basic operations,
such as add( ),
contains( ), remove( ), and size( ), to remain constant even for large sets.


// Demonstrate HashSet.
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}

The following is the output from this program:
[A, F, E, D, C, B]
As explained, the elements are not stored in sorted order, and the precise output may
vary.
The elements are not stored in sorted order, and the precise output may vary.

LinkedHashSet Class


Extends HashSet

LinkedHashSet maintains a linked list of the entries in the set,in the order in which
they were inserted. when cycling through a LinkedHashSet using an iterator, the
elements will be returned in the order in which they were inserted. Try substituting
LinkedHashSet For HashSet in the preceding program. The output will be
[B, A, D, E, C, F]which is the order in which the elements were inserted.

TreeSet Class

TreeSet provides an implementation of the Set interface

Uses a tree for storage.

Objects are stored in sorted, ascending order.

Access and retrieval times are quite fast, which makes TreeSet an excellent choice
when storing large amounts of sorted information that must be found quickly.


Few of the Exceptions thrown by methods of Collection classes:
UnsupportedOperationException. As explained, this occurs if a collection cannot be
modified. A

ClassCastException is generated when one object is incompatible with another, such
as when an attempt is made to add an incompatible object to a collection.

Method to Add objects to collection : Objects are added to a collection by calling add(
). Notice that add( ) takes an argument of type Object. Because Object is a
superclass of all classes, any type of object may be stored in a collection. However,
primitive types may not. For example, a collection cannot directly store values of type
int, char, double, and so forth.

Map Interface

The Map interface maps unique keys to values.

A key is an object that you use to retrieve a value at a later date. Given a key and a
value, you can store the value in a Map object. After the value is stored, you can
retrieve it by using its key.

Maps revolve around two basic operations: get( ) and put( ).

To put a value into a map, use put( ), specifying the key and the value. To obtain a
value, call get( ),passing
the key as an argument. The value is returned.
SortedMap Interface

The SortedMap interface extends Map.

It ensures that the entries are maintained in ascending key order.





HashMap Class

HashMap class uses a hash table to implement the Map interface.

This allows the execution time of basic operations, such as get( ) and put( ), to
remain constant even for
large sets.

import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));

// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)hm.get("John Doe")).doubleValue();
hm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
hm.get("John Doe"));
}
}
Output from this program is shown here (the precise order may vary).
Todd Hall: 99.22
Ralph Smith: -19.08
John Doe: 3434.34
Jane Baker: 1378.0
Tom Smith: 123.22
John Does current balance: 4434.34


LinkedHashMap Class

Extends HashMap.

LinkedHashMap maintains a linked list of the entries in the map, in the order in which
they were inserted. This allows insertion-order iteration over the map. That is,
wheniterating a LinkedHashMap, the elements will be returned in the order in
which theywere inserted..

























Which are used widely ?

I think you're fine to use HashMap, HashSet, and ArrayList as your primary
implementations. When you need a sorted set, it's good to know that TreeSet is
available.



Summarizing All





Arraylist

public class Collections {

/**
* @param args
*/
public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();
driver.get("http://www.quikr.com/");
WebElement listelement = driver.findElement(By.name("categoryId"));
//List<WebElement> listoptions = listelement.findElements(By.tagName("option"));

ArrayList<WebElement> listoptions = (ArrayList<WebElement>)
listelement.findElements(By.tagName("option"));
for (int i = 1;i<listoptions.size();i++)
{
//System.out.println(listoptions.get(i).getText());

}


Iterator<WebElement> iterators1 = ((ArrayList<WebElement>)
listoptions).iterator();

while (iterators1.hasNext()){
WebElement id1 = iterators1.next();
System.out.println(id1.getText());

}


}

}

HashSet
import java.util.HashSet;


class HashSetDemo {
public static void main(String args[]) {
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("A"); //This is duplicate so will not be added....

System.out.println(hs);
}
}

Output :

[D, E, F, A, B, C]

The sequence of element is not stored as per element added.






TreeSet

// Demonstrate TreeSet.
import java.util.*;

class TreeSetDemo {
public static void main(String args[]) {
// Create a tree set
TreeSet ts = new TreeSet();
// Add elements to the tree set
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("F");
ts.add("D"); // Duplicate is ignored
System.out.println(ts);
}
}


Output :

[A, B, C, D, E, F]

The sequence of element is stored in sorted order.



HashMap/HashTable

The following program illustrates HashMap. It maps names to account balances.
Notice how a set-view is obtained and used.


import java.util.*;

class HashMapDemo {

public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
hm.put("Ralph Smith", new Double(-19.08)); //Duplicate Entries will be ignored
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)hm.get("John Doe")).doubleValue();
hm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
hm.get("John Doe"));
}
}


Output from this program is shown here (the precise order may vary).
Todd Hall: 99.22
Ralph Smith: -19.08
John Doe: 3434.34
Jane Baker: 1378.0
Tom Smith: 123.22
John Does current balance: 4434.34


TreeMap


The following program reworks the preceding example so that it uses TreeMap:

import java.util.*;

class TreeMapDemo {

public static void main(String args[]) {
// Create a tree map
TreeMap tm = new TreeMap();
// Put elements to the map
tm.put("John Doe", new Double(3434.34));
tm.put("Tom Smith", new Double(123.22));
tm.put("Jane Baker", new Double(1378.00));
tm.put("Todd Hall", new Double(99.22));
tm.put("Ralph Smith", new Double(-19.08));
tm.put("Ralph Smith", new Double(-19.08)); //Duplicate entry is ignored
// Get a set of the entries
Set set = tm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)tm.get("John Doe")).doubleValue();
tm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
tm.get("John Doe"));
}
}

The following is the output from this program:
Jane Baker: 1378.0
John Doe: 3434.34
Ralph Smith: -19.08
Todd Hall: 99.22
Tom Smith: 123.22
John Does current balance: 4434.34

----------------------------------------------------------------------------------------
JUNIT FRAMEWORK

Q: What is testing?
A: Testing is the process of checking the functionality of the application whether
it is working as per requirements.
Q: What is unit testing?
A: Unit testing is the testing of single entity (class or method). Unit testing is very
essential to every software company to give a quality product to their customers.
Q: What is Manual testing?
A: Executing the test cases manually without any tool support is known as manual
testing.
Q: What is Automated testing?
A: Taking tool support and executing the test cases by using automation tool is
known as automation testing.
Q: Out of Manual and Automated testing which one is better and why?
A: Manual Testing is:
1. Time consuming and tedious.
2. Huge investment in human resources.
3. Less reliable.
4. Non-programmable.
Automated testing is
1. Fast
2. Less investment in human resources
3. More reliable
4. Programmable
Q: What is JUnit?
A: JUnit is a unit testing framework for the Java Programming Language. It is
written in Java and is an Open Source Software maintained by the JUnit.org
community.
Q: What are important features of JUnit?
A: Import features of JUnit are:
1. It is an open source framework.
2. Provides Annotation to identify the test methods.
3. Provides Assertions for testing expected results.
4. Provides Test runners for running tests.
5. JUnit tests can be run automatically and they check their own results and
provide immediate feedback.
6. JUnit tests can be organized into test suites containing test cases and even
other test suites.
7. JUnit shows test progress in a bar that is green if test is going fine and it
turns red when a test fails.
Q: What is a Unit Test Case?
A: A Unit Test Case is a part of code which ensures that the another part of code
(method) works as expected. A formal written unit test case is characterized by
a known input and by an expected output, which is worked out before the test is
executed. The known input should test a precondition and the expected output
should test a post condition.
Q: When are Unit Tests written in Development Cycle?
A: Tests are written before the code during development in order to help coders
write the best code.
Q: Why not just use System.out.println() for testing?
A: Debugging the code using system.out.println() will lead to manual scanning of
the whole output every time the program is run to ensure the code is doing the
expected operations. Moreover, in the long run, it takes lesser time to code JUnit
methods and test them on class files.
Q: How to install JUnit?
A: Follow the steps below:
1. Download the latest version of JUnit, referred to below as junit.zip.
2. Unzip the junit.zip distribution file to a directory referred to as
%JUNIT_HOME%.
3. Add JUnit to the classpath:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar
4. Test the installation by running the sample tests distributed with JUnit
(sample tests are located in the installation directory directly, not the junit.jar
file). Then simply type:
java org.junit.runner.JUnitCore org.junit.tests.AllTests
All the tests should pass with an "OK" message. If the tests don't pass, verify that
junit.jar is in the CLASSPATH.
Q: Why does JUnit only report the first failure in a single test?
A: Reporting multiple failures in a single test is generally a sign that the test does
too much and it is too big a unit test. JUnit is designed to work best with a number
of small tests. It executes each test within a separate instance of the test class.
It reports failure on each test.
Q: In Java, assert is a keyword. Won't this conflict with JUnit's assert()
method?
A: JUnit 3.7 deprecated assert() and replaced it with assertTrue(), which works
exactly the same way. JUnit 4 is compatible with the assert keyword. If you run
with the -ea JVM switch, assertions that fail will be reported by JUnit.
Q: How do I test things that must be run in a J2EE container (e.g.
servlets, EJBs)?
A: Refactoring J2EE components to delegate functionality to other objects that
don't have to be run in a J2EE container will improve the design and testability of
the software. Cactus is an open source JUnit extension that can be used for unit
testing server-side java code.
Q: What are JUnit classes? List some of them.
A: JUnit classes are important classes which are used in writing and testing JUnits.
Some of the important classes are:
1. Assert - A set of assert methods.
2. TestCase - It defines the fixture to run multiple tests.
3. TestResult - It collects the results of executing a test case.
4. TestSuite - It is a Composite of Tests.
Q: What are annotations and how are they useful in JUnit?
A: Annotations are like meta-tags that you can add to you code and apply them
to methods or in class. The annotation in JUnit gives us information about test
methods , which methods are going to run before & after test methods, which
methods run before & after all the methods, which methods or class will be ignore
during execution.
Q: How will you run JUnit from command window?
A: Follow the steps below:
1. Set the CLASSPATH
2. Invoke the runner:
3. java org.junit.runner.JUnitCore
Q: What is JUnitCore class?
A: JUnitCore is an inbuilt class in JUnit package. It is based on Facade design
pattern. This class is used to run only specified test classes.
Q: What is Test suite?
A: Test suite means bundle a few unit test cases and run it together. In JUnit,
both @RunWith and @Suite annotation are used to run the suite test.
Q: What is @Ignore annotation and how is this useful?
A: Sometimes it happens that our code is not ready and test case written to test
that method/code will fail if run. The @Ignore annotation helps in this regards.
Following are some of the usefulness of @Ignore annotation:
1. You can easily identify all @Ignore annotations in the source code, while
unannotated or commented out tests are not so simple to find.
2. There are cases when you can't fix a code that is failing, but you still want
to method to be around, precisely so that it does not get forgotten. In such cases
@Ignore makes sense.
Q: What are Parameterized tests?
A: Parameterized tests allow developer to run the same test over and over again
using different values.
Q: How do you use test fixtures?
A: Fixtures is a fixed state of a set of objects used as a baseline for running tests.
The purpose of a test fixture is to ensure that there is a well known and fixed
environment in which tests are run so that results are repeatable. It includes:
1. setUp() method which runs before every test invocation.
2. tearDown() method which runs after every test method.
Q: How to compile a JUnit Test Class?
A: Compiling a JUnit test class is like compiling any other Java classes. The only
thing you need watch out is that the JUnit JAR file must be included in the
classpath.
Q: What happens if a JUnit Test Method is Declared as "private"?
A: If a JUnit test method is declared as "private", it compiles successfully. But the
execution will fail. This is because JUnit requires that all test methods must be
declared as "public".
Q: How do you test a "protected" method?
A: When a method is declared as "protected", it can only be accessed within the
same package where the class is defined. Hence to test a "protected" method of
a target class, define your test class in the same package as the target class.
Q: How do you test a "private" method?
A: When a method is declared as "private", it can only be accessed within the
same class. So there is no way to test a "private" method of a target class from
any test class. Hence you need to perform unit testing manually. Or you have to
change your method from "private" to "protected".
Q: What happens if a JUnit test method is declared to return "String"?
A: If a JUnit test method is declared to return "String", the compilation will pass
ok. But the execution will fail. This is because JUnit requires that all test methods
must be declared to return "void".
Q: How can you use JUnit to test that the code throws desired
exception?
A: JUnit provides a option of tracing the Exception handling of code. You can test
if a code throws desired exception or not. The expected parameter is used along
with @Test annotation as follows: @Test(expected)
Q: What are Parameterized tests in JUnit?
A: Parameterized tests allow developer to run the same test over and over again
using different values.
Q: How to create Parameterized tests?
A: There are five steps, which you need to follow to create Parameterized tests:
1. Annotate test class with @RunWith(Parameterized.class).
2. Create a public static method annotated with @Parameters that returns a
Collection of Objects (as Array) as test data set.
3. Create a public constructor that takes in what is equivalent to one "row" of
test data.
4. Create an instance variable for each "column" of test data.
5. Create your tests case(s) using the instance variables as the source of the
test data.
The test case will be invoked once per each row of data.
Q: Can you use a main() Method for Unit Testing?
A: Yes you can test using main() method. One obvious advantage seems to be
that you can whitebox test the class. That is, you can test the internals of it
(private methods for example). You can't do that with unit-tests. But primarily
the test framework tests the interface and the behavior from the user's
perspective.
Q: Do you need to write a test class for every class that needs to be
tested?
A: No. We need not write an independent test class for every class that needs to
be tested. If there is a small group of tests sharing a common test fixture, you
may move those tests to a new test class.
Q: When are tests garbage collected?
A: The test runner holds strong references to all Test instances for the duration
of the test execution. This means that for a very long test run with many Test
instances, none of the tests may be garbage collected until the end of the entire
test run. Explicitly setting an object to null in the tearDown() method, for
example, allows it to be garbage collected before the end of the entire test run.


JUnit Tutorial
JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of
test-driven development, and is one of a family of unit testing frameworks collectively known as xUnit that originated
with JUnit.
This tutorial will teach you how to use JUnit in your day-2-day life of any project unit testing while working with Java
programming language.
Audience
This tutorial has been prepared for the beginners to help them understand basic functionality of JUnit tool. After
completing this tutorial you will find yourself at a moderate level of expertise in using JUnit testing framework from
where you can take yourself to next levels.
Prerequisites
We assume you are going to use JUnit to handle all levels of Java projects development. So it will be good if you have
knowledge of software development using any programming language specially Java programming and software
testing process.
Compile/Execute Java & JUnit Programs
For most of the examples given in this tutorial you will find Try it option, so just make use of it and enjoy your learning.
Try following example using Try it option available at the top right corner of the below sample code box:
public class MyFirstJavaProgram {

public static void main(String []args) {
System.out.println("Hello World");
}
}


Testing is the process of checking the functionality of the application whether it is working as per requirements and to
ensure that at developer level, unit testing comes into picture. Unit testing is the testing of single entity (class or method).
Unit testing is very essential to every software company to give a quality product to their customers.
Unit testing can be done in two ways
Manual testing Automated testing
Executing the test cases manually without any tool support is
known as manual testing.
Time consuming and tedious: Since test cases are
executed by human resources so it is very slow and tedious.
Huge investment in human resources: As test cases
need to be executed manually so more testers are required in
manual testing.
Less reliable: Manual testing is less reliable as tests
may not be performed with precision each time because of
human errors.
Non-programmable: No programming can be done to
write sophisticated tests which fetch hidden information.
Taking tool support
and executing the test
cases by using
automation tool is
known as automation
testing.
Fast
Automation runs test
cases significantly
faster than human
resources.
Less
investment in human
resources:Test cases
are executed by using
automation tool so less
tester are required in
automation testing.
More reliable:
Automation tests
perform precisely
same operation each
time they are run.
Programmable:
Testers can program
sophisticated tests to
bring out hidden
information.
WHAT IS JUNIT ?
JUnit is a unit testing framework for the Java Programming Language. It is important in the test driven development,
and is one of a family of unit testing frameworks collectively known as xUnit.
JUnit promotes the idea of "first testing then coding", which emphasis on setting up the test data for a piece of code
which can be tested first and then can be implemented . This approach is like "test a little, code a little, test a little, code
a little..." which increases programmer productivity and stability of program code that reduces programmer stress and
the time spent on debugging.
FEATURES
JUnit is an open source framework which is used for writing & running tests.
Provides Annotation to identify the test methods.
Provides Assertions for testing expected results.
Provides Test runners for running tests.
JUnit tests allow you to write code faster which increasing quality
JUnit is elegantly simple. It is less complex & takes less time.
JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's
no need to manually comb through a report of test results.
JUnit tests can be organized into test suites containing test cases and even other test suites.
Junit shows test progress in a bar that is green if test is going fine and it turns red when a test fails.
WHAT IS A UNIT TEST CASE ?
A Unit Test Case is a part of code which ensures that the another part of code (method) works as expected. To achieve
those desired results quickly, test framework is required .JUnit is perfect unit test framework for java programming
language.
A formal written unit test case is characterized by a known input and by an expected output, which is worked out before
the test is executed. The known input should test a precondition and the expected output should test a postcondition.
There must be at least two unit test cases for each requirement: one positive test and one negative test. If a requirement
has sub-requirements, each sub-requirement must have at least two test cases as positive and negative.


TRY IT OPTION ONLINE
You really do not need to set up your own environment to start learning Java & JUnit programming language. Reason
is very simple, we already have setup Java Programming environment online, so that you can compile and execute all
the available examples online at the same time when you are doing your theory work. This gives you confidence in
what you are reading and to check the result with different options. Feel free to modify any example and execute it
online.
Try following example using Try it option available at the top right corner of the below sample code box:
public class MyFirstJavaProgram {

public static void main(String []args) {
System.out.println("Hello World");
}
}
For most of the examples given in this tutorial, you will find Try it option, so just make use of it and enjoy your learning.
LOCAL ENVIRONMENT SETUP
JUnit is a framework for Java, so the very first requirement is to have JDK installed in your machine.
SYSTEM REQUIREMENT
JDK 1.5 or above.
Memory no minimum requirement.
Disk Space no minimum requirement.
Operating System no minimum requirement.
STEP 1 - VERIFY JAVA INSTALLATION IN YOUR MACHINE
Now open console and execute the following java command.
OS Task Command
Windows Open Command Console c:\> java -version
Linux Open Command Terminal $ java -version
Mac Open Terminal machine:~ joseph$ java -version
Let's verify the output for all the operating systems:
OS Output
Windows
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
Linux
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
Mac
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode,
sharing)
If you do not have Java installed, install the Java Software Development Kit (SDK)
fromhttp://www.oracle.com/technetwork/java/javase/downloads/index.html. We are assuming Java 1.6.0_21 as
installed version for this tutorial.
STEP 2: SET JAVA ENVIRONMENT
Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your
machine. For example
OS Output
Windows
Set the environment variable JAVA_HOME to C:\Program
Files\Java\jdk1.6.0_21
Linux export JAVA_HOME=/usr/local/java-current
Mac export JAVA_HOME=/Library/Java/Home
Append Java compiler location to System Path.
OS Output
Windows
Append the string ;C:\Program Files\Java\jdk1.6.0_21\bin to the end
of the system variable, Path.
Linux export PATH=$PATH:$JAVA_HOME/bin/
Mac not required
Verify Java Installation using java -version command explained above.
STEP 3: DOWNLOAD JUNIT ARCHIVE
Download latest version of JUnit jar file from http://www.junit.org. At the time of writing this tutorial, I downloaded Junit-
4.10.jar and copied it into C:\>JUnit folder.
OS Archive name
Windows junit4.10.jar
Linux junit4.10.jar
Mac junit4.10.jar
STEP 4: SET JUNIT ENVIRONMENT
Set the JUNIT_HOME environment variable to point to the base directory location where JUNIT jar is stored on your
machine. Assuming, we've stored junit4.10.jar in JUNIT folder on various Operating Systems as follows.
OS Output
Windows Set the environment variable JUNIT_HOME to C:\JUNIT
Linux export JUNIT_HOME=/usr/local/JUNIT
Mac export JUNIT_HOME=/Library/JUNIT
STEP 5: SET CLASSPATH VARIABLE
Set the CLASSPATH environment variable to point to the JUNIT jar location. Assuming, we've stored junit4.10.jar in
JUNIT folder on various Operating Systems as follows.
OS Output
Windows
Set the environment variable CLASSPATH to
%CLASSPATH%;%JUNIT_HOME%\junit4.10.jar;.;
Linux export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit4.10.jar:.
Mac export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit4.10.jar:.
STEP 6: TEST JUNIT SETUP
Create a java class file name TestJunit in C:\ > JUNIT_WORKSPACE

import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
@Test
public void testAdd() {
String str= "Junit is working fine";
assertEquals("Junit is working fine",str);
}
}
Create a java class file name TestRunner in C:\ > JUNIT_WORKSPACE to execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
STEP 7: VERIFY THE RESULT
Compile the classes using javac compiler as follows
C:\JUNIT_WORKSPACE>javac TestJunit.java TestRunner.java
Now run the Test Runner to see the result
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.


WHAT IS JUNIT TEST FRAMEWORK?
JUnit is a Regression Testing Framework used by developers to implement unit testing in Java and accelerate
programming speed and increase the quality of code. JUnit Framework can be easily integrated with either of the
followings:
Eclipse
Ant
Maven
FEATURES
JUnit test framework provides following important features
Fixtures
Test suites
Test runners
JUnit classes
FIXTURES
Fixtures is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to
ensure that there is a well known and fixed environment in which tests are run so that results are repeatable. It includes
setUp() method which runs before every test invocation.
tearDown() method which runs after every test method.
Let's check one example:
import junit.framework.*;

public class JavaTest extends TestCase {
protected int value1, value2;

// assigning the values
protected void setUp(){
value1=3;
value2=3;
}

// test method to add two values
public void testAdd(){
double result= value1 + value2;
assertTrue(result == 6);
}
}
TEST SUITE
Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation
are used to run the suite test. Here is an example which uses TestJunit1 & TestJunit2 test classes.
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

//JUnit Suite Test
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestJunit1.class ,TestJunit2.class
})
public class JunitTestSuite {
}
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;

public class TestJunit1 {

String message = "Robert";
MessageUtil messageUtil = new MessageUtil(message);

@Test
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
assertEquals(message, messageUtil.printMessage());
}
}
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;

public class TestJunit2 {

String message = "Robert";
MessageUtil messageUtil = new MessageUtil(message);

@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
}
}
TEST RUNNER
Test runner is used for executing the test cases. Here is an example which assumes TestJunit test class already
exists.
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
JUNIT CLASSES
JUnit classes are important classes which is used in writing and testing JUnits. Some of the important classes are
Assert which contain a set of assert methods.
TestCase which contain a test case defines the fixture to run multiple tests.
TestResult which contain methods to collect the results of executing a test case.


Now we'll show you a step by step process to get a kick start in Junit using a basic example.
CREATE A CLASS
o Create a java class to be tested say MessageUtil.java in C:\ > JUNIT_WORKSPACE
/*
* This class prints the given message on console.
*/
public class MessageUtil {

private String message;

//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}

// prints the message
public String printMessage(){
System.out.println(message);
return message;
}
}
CREATE TEST CASE CLASS
o Create a java test class say TestJunit.java.
o Add a test method testPrintMessage() to your test class.
o Add an Annotaion @Test to method testPrintMessage().
o Implement the test condition and check the condition using assertEquals API of Junit.
Create a java class file name TestJunit.java in C:\ > JUNIT_WORKSPACE
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {

String message = "Hello World";
MessageUtil messageUtil = new MessageUtil(message);

@Test
public void testPrintMessage() {
assertEquals(message,messageUtil.printMessage());
}
}
CREATE TEST RUNNER CLASS
o Create a TestRunner java class.
o Use runClasses method of JUnitCore class of JUnit to run test case of above created test class
o Get the result of test cases run in Result Object
o Get failure(s) using getFailures() methods of Result object
o Get Success result using wasSuccessful() methods of Result object
Create a java class file name TestRunner.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Compile the MessageUtil, Test case and Test Runner classes using javac
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.
Hello World
true
Now update TestJunit in C:\ > JUNIT_WORKSPACE so that test fails. Change the message string.
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {

String message = "Hello World";
MessageUtil messageUtil = new MessageUtil(message);

@Test
public void testPrintMessage() {
message = "New Word";
assertEquals(message,messageUtil.printMessage());
}
}
Let's keep rest of the classes as is, and try to run same Test Runner
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.
Hello World
testPrintMessage(TestJunit): expected:<[New Wor]d> but was:<[Hello Worl]d>
false
IMPORTANT API'S OF JUNIT
The most important package in JUnit is junit.framework which contain all the core classes. Some of the important
class are
Serial
No
Class Name Functionality
1 Assert A set of assert methods.
2 TestCase
A test case defines the fixture to run multiple
tests.
3 TestResult
A TestResult collects the results of executing
a test case.
4 TestSuite A TestSuite is a Composite of Tests.
ASSERT CLASS
Following is the declaration for org.junit.Assert class:
public class Assert extends java.lang.Object
This class provides a set of assertion methods useful for writing tests. Only failed assertions are recorded. Some of the
important methods of Assert class are:
S.N. Methods & Description
1
void assertEquals(boolean expected, boolean actual) Check that two
primitives/Objects are equal
2 void assertFalse(boolean condition) Check that a condition is false
3 void assertNotNull(Object object) Check that an object isn't null.
4 void assertNull(Object object) Check that an object is null
5 void assertTrue(boolean condition) Check that a condition is true.
6 void fail() Fails a test with no message.
Let's try to cover few of the above mentioned methods in an example. Create a java class file name TestJunit1.java
in C:\ > JUNIT_WORKSPACE
import org.junit.Test;
import static org.junit.Assert.*;
public class TestJunit1 {
@Test
public void testAdd() {
//test data
int num= 5;
String temp= null;
String str= "Junit is working fine";

//check for equality
assertEquals("Junit is working fine", str);

//check for false condition
assertFalse(num > 6);

//check for not null value
assertNotNull(str);
}
}
Next, let's create a java class file name TestRunner1.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner1 {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit1.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac
C:\JUNIT_WORKSPACE>javac TestJunit1.java TestRunner1.java
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner1
Verify the output.
true
TESTCASE CLASS
Following is the declaration for org.junit.TestCaset class:
public abstract class TestCase extends Assert implements Test
A test case defines the fixture to run multiple tests. Some of the important methods of TestCase class are
S.N. Methods & Description
1
int countTestCases() Counts the number of test cases executed by
run(TestResult result).
2 TestResult createResult() Creates a default TestResult object.
3 String getName() Gets the name of a TestCase.
4
TestResult run() A convenience method to run this test, collecting the results
with a default TestResult object.
5
void run(TestResult result) Runs the test case and collects the results in
TestResult.
6 void setName(String name) Sets the name of a TestCase.
7 void setUp() Sets up the fixture, for example, open a network connection.
8
void tearDown() Tears down the fixture, for example, close a network
connection.
9 String toString() Returns a string representation of the test case.
Let's try to cover few of the above mentioned methods in an example. Create a java class file name TestJunit2.java
in C:\ > JUNIT_WORKSPACE
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
public class TestJunit2 extends TestCase {
protected double fValue1;
protected double fValue2;

@Before
public void setUp() {
fValue1= 2.0;
fValue2= 3.0;
}

@Test
public void testAdd() {
//count the number of test cases
System.out.println("No of Test Case = "+ this.countTestCases());

//test getName
String name= this.getName();
System.out.println("Test Case Name = "+ name);

//test setName
this.setName("testNewAdd");
String newName= this.getName();
System.out.println("Updated Test Case Name = "+ newName);
}
//tearDown used to close the connection or clean up activities
public void tearDown( ) {
}
}
Next, let's create a java class file name TestRunner2.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner2 {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit2.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac
C:\JUNIT_WORKSPACE>javac TestJunit2.java TestRunner2.java
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner2
Verify the output.
No of Test Case = 1
Test Case Name = testAdd
Updated Test Case Name = testNewAdd
true
TESTRESULT CLASS
Following is the declaration for org.junit.TestResult class:
public class TestResult extends Object
A TestResult collects the results of executing a test case. It is an instance of the Collecting Parameter pattern. The test
framework distinguishes between failures and errors. A failure is anticipated and checked for with assertions. Errors
are unanticipated problems like an ArrayIndexOutOfBoundsException. Some of the important methods
of TestResult class are
S.N. Methods & Description
1 void addError(Test test, Throwable t) Adds an error to the list of errors.
2
void addFailure(Test test, AssertionFailedError t) Adds a failure to the list
of failures.
3 void endTest(Test test) Informs the result that a test was completed.
4 int errorCount() Gets the number of detected errors.
5 Enumeration<TestFailure> errors() Returns an Enumeration for the errors.
6 int failureCount() Gets the number of detected failures.
7 void run(TestCase test) Runs a TestCase.
8 int int runCount() Gets the number of run tests.
9 void startTest(Test test) Informs the result that a test will be started.
10 void stop() Marks that the test run should stop.
Create a java class file name TestJunit3.java in C:\ > JUNIT_WORKSPACE
import org.junit.Test;
import junit.framework.AssertionFailedError;
import junit.framework.TestResult;

public class TestJunit3 extends TestResult {
// add the error
public synchronized void addError(Test test, Throwable t) {
super.addError((junit.framework.Test) test, t);
}

// add the failure
public synchronized void addFailure(Test test, AssertionFailedError t) {
super.addFailure((junit.framework.Test) test, t);
}
@Test
public void testAdd() {
// add any test
}

// Marks that the test run should stop.
public synchronized void stop() {
//stop the test here
}
}
Next, let's create a java class file name TestRunner3.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner3 {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit3.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac
C:\JUNIT_WORKSPACE>javac TestJunit3.java TestRunner3.java
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner3
Verify the output.
true

TESTSUITE CLASS
Following is the declaration for org.junit.TestSuite class:
public class TestSuite extends Object implements Test
A TestSuite is a Composite of Tests. It runs a collection of test cases. Some of the important methods of TestSuite class
are
S.N. Methods & Description
1 void addTest(Test test) Adds a test to the suite.
2
void addTestSuite(Class<? extends TestCase> testClass) Adds the tests
from the given class to the suite.
3
int countTestCases() Counts the number of test cases that will be run by this
test.
4 String getName() Returns the name of the suite.
5
void run(TestResult result) Runs the tests and collects their result in a
TestResult.
6 void setName(String name) Sets the name of the suite.
7 Test testAt(int index) Returns the test at the given index.
8 int testCount() Returns the number of tests in this suite.
9
static Test warning(String message) Returns a test which will fail and log a
warning message.
Create a java class file name JunitTestSuite.java in C:\ > JUNIT_WORKSPACE to create Test suite
import junit.framework.*;
public class JunitTestSuite {
public static void main(String[] a) {
// add the test's in the suite
TestSuite suite = new TestSuite(TestJunit1.class, TestJunit2.class,
TestJunit3.class );
TestResult result = new TestResult();
suite.run(result);
System.out.println("Number of test cases = " + result.runCount());
}
}
Compile the Test suite classes using javac
C:\JUNIT_WORKSPACE>javac JunitTestSuite.java
Now run the Test Suite.
C:\JUNIT_WORKSPACE>java JunitTestSuite
Verify the output.
No of Test Case = 1
Test Case Name = testAdd
Updated Test Case Name = testNewAdd
Number of test cases = 3
Here we will see one complete example of JUnit testing using POJO class, Business logic class and a test class which
will be run by test runner.
Create EmployeeDetails.java in C:\ > JUNIT_WORKSPACE which is a POJO class.
public class EmployeeDetails {

private String name;
private double monthlySalary;
private int age;

/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the monthlySalary
*/
public double getMonthlySalary() {
return monthlySalary;
}
/**
* @param monthlySalary the monthlySalary to set
*/
public void setMonthlySalary(double monthlySalary) {
this.monthlySalary = monthlySalary;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
}
EmployeeDetails class is used to
o get/set the value of employee's name.
o get/set the value of employee's monthly salary.
o get/set the value of employee's age.
Create a EmpBusinessLogic.java in C:\ > JUNIT_WORKSPACE which contains business logic
public class EmpBusinessLogic {
// Calculate the yearly salary of employee
public double calculateYearlySalary(EmployeeDetails employeeDetails){
double yearlySalary=0;
yearlySalary = employeeDetails.getMonthlySalary() * 12;
return yearlySalary;
}

// Calculate the appraisal amount of employee
public double calculateAppraisal(EmployeeDetails employeeDetails){
double appraisal=0;
if(employeeDetails.getMonthlySalary() < 10000){
appraisal = 500;
}else{
appraisal = 1000;
}
return appraisal;
}
}
EmpBusinessLogic class is used for calculating
o the yearly salary of employee.
o the appraisal amount of employee.
Create a TestEmployeeDetails.java in C:\ > JUNIT_WORKSPACE which contains test cases to be tested
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class TestEmployeeDetails {
EmpBusinessLogic empBusinessLogic =new EmpBusinessLogic();
EmployeeDetails employee = new EmployeeDetails();

//test to check appraisal
@Test
public void testCalculateAppriasal() {
employee.setName("Rajeev");
employee.setAge(25);
employee.setMonthlySalary(8000);
double appraisal= empBusinessLogic.calculateAppraisal(employee);
assertEquals(500, appraisal, 0.0);
}

// test to check yearly salary
@Test
public void testCalculateYearlySalary() {
employee.setName("Rajeev");
employee.setAge(25);
employee.setMonthlySalary(8000);
double salary= empBusinessLogic.calculateYearlySalary(employee);
assertEquals(96000, salary, 0.0);
}
}
TestEmployeeDetails class is used for testing the methods of EmpBusinessLogic class. It
o tests the yearly salary of the employee.
o tests the appraisal amount of the employee.
Next, let's create a java class file name TestRunner.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestEmployeeDetails.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac
C:\JUNIT_WORKSPACE>javac EmployeeDetails.java
EmpBusinessLogic.java TestEmployeeDetails.java TestRunner.java
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.
true

----------------------------------------------------------------------------------------
SELENIUM INTERVIEW QUESTIONS-- ANSWERS
1. How to find the Name of the links in a
Google Page?

package com.Selenium;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.Test;

public class WebDriverTest
{
@Test
public void testCollection()

{
System.setProperty("webdriver.ie.driver",
"C:\\Automation2013\\Ieserver\\IEDriverServer.exe");
InternetExplorerDriver driver = new InternetExplorerDriver();

driver.get("http://www.google.com/");
List<WebElement> anchorlist = driver.findElements(By.tagName("a"));
for(WebElement element : anchorlist){
System.out.println(element.getText());


}
}

}

2. HOW TO FIND NUMBER OF LINKS IN A GOOGLE PAGE?
package com.Selenium;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.Test;

public class WebDriverTest
{
@Test
public void testCollection()

{
System.setProperty("webdriver.ie.driver", "C:\\Automation Nov
2013\\Ieserver\\IEDriverServer.exe");
InternetExplorerDriver driver = new InternetExplorerDriver();

driver.get("http://www.google.com/");
// How to find the number of links in a web page
int anchorlist1 = driver.findElements(By.tagName("a")).size();
System.out.println(anchorlist1);


}
}

----------------------------------------------------------------------------------------
JUNIT 4 VS TESTNG COMPARISON

JUnit 4 and TestNG are both very popular unit test framework in Java. Both frameworks
look very similar in functionality. Which one is better? Which unit test framework should I
use in Java project?
Here I did a feature comparison between JUnit 4 and TestNG.


Functionality TestNg Junit
Annotation
Support
Yes Yes
Exception Yes Yes
Ignore Test Yes Yes
Timeout Test Yes Yes
Suite Test Yes Yes
Group Test Yes NO
Parameterized
(Primitive
Value)
Yes Yes

Parameterized
(Object)
Yes No
Dependancy Yes No
Feature JUnit 4 TestNG
test annotation @Test @Test
run before all
tests
in this suite
have run
@BeforeSuite
run after all tests
in this suite
have run
@AfterSuite
run before the
test
@BeforeTest
run after the test @AfterTest
run before the
first test
method that
belongs
to any of these
groups is
invoked
@BeforeGroups
run after the last
test
method that
belongs
to any of these
groups
is invoked
@AfterGroups
run before the
first
test method in
the
current class is
invoked
@BeforeClass @BeforeClass
run after all the
test
methods in the
current class
have been run
@AfterClass @AfterClass
run before each
test method
@Before @BeforeMethod
run after each
test
method
@After @AfterMethod
ignore test @ignore @Test(enbale=false)
expected
exception
@Test(expected =
ArithmeticException.class)
@Test(expectedExceptions =
ArithmeticException.class)
timeout @Test(timeout = 1000) @Test(timeout = 1000)
Only @Parameters declares in method which needs parameter for testing, the parametric
data will provide in TestNGs XML configuration files. By doing this, we can reuse a single
test case with different data sets and even get different results. In addition, even end user,
QA or QE can provide their own data in XML file for testing.
P.S TestNGTest6_3_0 is an simple object with just get set method for demo.
1. Annotation Support
The annotation supports are implemented in both JUnit 4 and TestNG look similar.
The main annotation differences between JUnit4 and TestNG are
1. In JUnit 4, we have to declare @BeforeClass and @AfterClass method as static
method. TestNG is more flexible in method declaration, it does not have this constraints.
2. 3 additional setUp/tearDown level: suite and group (@Before/AfterSuite,
@Before/AfterTest, @Before/AfterGroup). See more detail here.
JUnit 4
Ads not by this site
@BeforeClass
public static void oneTimeSetUp() {
// one-time initialization code
System.out.println("@BeforeClass - oneTimeSetUp");
}
TestNG
@BeforeClass
public void oneTimeSetUp() {
// one-time initialization code
System.out.println("@BeforeClass - oneTimeSetUp");
}
In JUnit 4, the annotation naming convention is a bit confusing, e.g Before, After and
Expected, we do not really understand what is Before and After do, and what we
Expected from test method? TestiNG is easier to understand, it uses BeforeMethod,
AfterMethod and ExpectedException instead.
2. Exception Test
The exception testing means what exception throws from the unit test, this feature is
implemented in both JUnit 4 and TestNG.
JUnit 4
@Test(expected = ArithmeticException.class)
public void divisionWithException() {
int i = 1/0;
}
TestNG
@Test(expectedExceptions = ArithmeticException.class)
public void divisionWithException() {
int i = 1/0;
}
3. Ignore Test
The Ignored means whether it should ignore the unit test, this feature is implemented in
both JUnit 4 and TestNG .
JUnit 4
@Ignore("Not Ready to Run")
@Test
public void divisionWithException() {
System.out.println("Method is not ready yet");
}
TestNG
@Test(enabled=false)
public void divisionWithException() {
System.out.println("Method is not ready yet");
}
4. Time Test
The Time Test means if an unit test takes longer than the specified number of milliseconds
to run, the test will terminated and mark as fails, this feature is implemented in both JUnit 4
and TestNG .
JUnit 4
@Test(timeout = 1000)
public void infinity() {
while (true);
}
TestNG
@Test(timeOut = 1000)
public void infinity() {
while (true);
}
5. Suite Test
The Suite Test means bundle a few unit test and run it together. This feature is
implemented in both JUnit 4 and TestNG. However both are using very different method to
implement it.
JUnit 4
The @RunWith and @Suite are use to run the suite test. The below class means both
unit test JunitTest1 and JunitTest2 run together after JunitTest5 executed. All the
declaration is define inside the class.
Ads not by this site
@RunWith(Suite.class)
@Suite.SuiteClasses({
JunitTest1.class,
JunitTest2.class
})
public class JunitTest5 {
}
TestNG
XML file is use to run the suite test. The below XML file means both unit test TestNGTest1
and TestNGTest2 will run it together.
<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="My test suite">
<test name="testing">
<classes>
<class name="com.fsecure.demo.testng.TestNGTest1" />
<class name="com.fsecure.demo.testng.TestNGTest2" />
</classes>
</test>
</suite>
TestNG can do more than bundle class testing, it can bundle method testing as well. With
TestNG unique Grouping concept, every method is tie to a group, it can categorize tests
according to features. For example,
Here is a class with four methods, three groups (method1, method2 and method3)
@Test(groups="method1")
public void testingMethod1() {
System.out.println("Method - testingMethod1()");
}

@Test(groups="method2")
public void testingMethod2() {
System.out.println("Method - testingMethod2()");
}

@Test(groups="method1")
public void testingMethod1_1() {
System.out.println("Method - testingMethod1_1()");
}

@Test(groups="method4")
public void testingMethod4() {
System.out.println("Method - testingMethod4()");
}
With the following XML file, we can execute the unit test with group method1 only.
Ads not by this site
<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="My test suite">
<test name="testing">
<groups>
<run>
<include name="method1"/>
</run>
</groups>
<classes>
<class name="com.fsecure.demo.testng.TestNGTest5_2_0" />
</classes>
</test>
</suite>
With Grouping test concept, the integration test possibility is unlimited. For example, we
can only test the DatabaseFuntion group from all of the unit test classes.
6. Parameterized Test
The Parameterized Test means vary parameter value for unit test. This feature is
implemented in both JUnit 4 and TestNG. However both are using very different method to
implement it.
JUnit 4
The @RunWith and @Parameter is use to provide parameter value for unit test,
@Parameters have to return List[], and the parameter will pass into class constructor as
argument.
@RunWith(value = Parameterized.class)
public class JunitTest6 {

private int number;

public JunitTest6(int number) {
this.number = number;
}

@Parameters
public static Collection<Object[]> data() {
Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };
return Arrays.asList(data);
}

@Test
public void pushTest() {
System.out.println("Parameterized Number is : " + number);
}
}
It has many limitations here; we have to follow the JUnit way to declare the parameter,
and the parameter has to pass into constructor in order to initialize the class member as
parameter value for testing. The return type of parameter class is List [], data has been
limited to String or a primitive value for testing.
TestNG
XML file or @DataProvider is use to provide vary parameter for testing.
XML file for parameterized test.
Unit Test
public class TestNGTest6_1_0 {

@Test
@Parameters(value="number")
public void parameterIntTest(int number) {
System.out.println("Parameterized Number is : " + number);
}

}
XML File
Ads not by this site
<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="My test suite">
<test name="testing">

<parameter name="number" value="2"/>

<classes>
<class name="com.fsecure.demo.testng.TestNGTest6_0" />
</classes>
</test>
</suite>
@DataProvider for parameterized test.
While pulling data values into an XML file can be quite handy, tests occasionally require
complex types, which cant be represented as a String or a primitive value. TestNG handles
this scenario with its @DataProvider annotation, which facilitates the mapping of complex
parameter types to a test method.
@DataProvider for Vector, String or Integer as parameter
@Test(dataProvider = "Data-Provider-Function")
public void parameterIntTest(Class clzz, String[] number) {
System.out.println("Parameterized Number is : " + number[0]);
System.out.println("Parameterized Number is : " + number[1]);
}

//This function will provide the patameter data
@DataProvider(name = "Data-Provider-Function")
public Object[][] parameterIntTestProvider() {
return new Object[][]{
{Vector.class, new String[] {"java.util.AbstractList",
"java.util.AbstractCollection"}},
{String.class, new String[] {"1", "2"}},
{Integer.class, new String[] {"1", "2"}}
};
}
@DataProvider for object as parameter
@Test(dataProvider = "Data-Provider-Function")
public void parameterIntTest(TestNGTest6_3_0 clzz) {
System.out.println("Parameterized Number is : " + clzz.getMsg());
System.out.println("Parameterized Number is : " + clzz.getNumber());
}

//This function will provide the patameter data
@DataProvider(name = "Data-Provider-Function")
public Object[][] parameterIntTestProvider() {

TestNGTest6_3_0 obj = new TestNGTest6_3_0();
obj.setMsg("Hello");
obj.setNumber(123);

return new Object[][]{
{obj}
};
}
TestNGs parameterized test is very user friendly and flexible (either in XML file or inside the
class). It can support many complex data type as parameter value and the possibility is
unlimited. As example above, we even can pass in our own object (TestNGTest6_3_0) for
parameterized test
7. Dependency Test
The Parameterized Test means methods are test base on dependency, which will execute
before a desired method. If the dependent method fails, then all subsequent tests will be
skipped, not marked as failed.
JUnit 4
JUnit framework is focus on test isolation; it did not support this feature at the moment.
TestNG
It use dependOnMethods to implement the dependency testing as following
Ads not by this site
@Test
public void method1() {
System.out.println("This is method 1");
}

@Test(dependsOnMethods={"method1"})
public void method2() {
System.out.println("This is method 2");
}
The method2() will execute only if method1() is run successfully, else method2() will
skip the test.
Conclusion
After go thought all the features comparison, i suggest to use TestNG as core unit test
framework for Java project, because TestNG is more advance in parameterize testing,
dependency testing and suite testing (Grouping concept). TestNG is meant for high-level
testing and complex integration test. Its flexibility is especially useful with large test suites.
In addition, TestNG also cover the entire core JUnit4 functionality. Its just no reason for me
to use JUnit anymore.

----------------------------------------------------------------------------------------
INTERVIEW QUESTIONS AT SEMANTIC SPACE
1. Tell me something about your self?
2. What are the version control system you are using?
3. what are the selenium components you are using?
4. what is the difference between Selenium RC and Selenium Web driver?
5. What are the limitations of selenium RC?
6. What is Array and Array list?
7. what is the difference between JUNIT and TESTNG?
8. How to connect a database with Selenium?
9. How can i increase my Array size dynamically?
10. What is the Update command syntax?
11. what is the inheritance?
12. How to work on multiple inheritance concept in java?
13. what is interface?
14. How to get the image name which is dynamically changing every time?
15. What is the difference between QTP and Selenium?
16. Generally how to generate the Selenium test result report? On what format
you are sending the results to your lead?

----------------------------------------------------------------------------------------
WEB LOGIC, WEB SERVER AND APPLICATION SERVER QUESTION & ANSWERS

WEB LOGIC?
Ans: BEA Systems' Web Logic is a server software application that runs on a middle tier,
between back- end databases and related applications and browser-based thin clients.


Web Logic is a leading e-commerce online transaction processing (OLTP) platform, developed
to connect users in a distributed computing environment and to facilitate the integration
of mainframe applications with distributed corporate data and applications.




What is Application server and Web server?


Application Server: An application server exposes a business logic to the client applications
through various protocals including HTTP.


Web Server: Web server mainly deals with sending HTML for dispaly in web browser.


a web serever exclusively handles HTTP requests.


APPLICATION SERVER WEB SERVER
Introduction
An application server is a
software framework that
provides an environment in
which applications can run, no
matter what the applications are
or what they do.
Web server can refer to either
the hardware (the computer) or
the software (the computer
application) that helps to deliver
content that can be accessed
through the Internet.
What is it?
A server that exposes business
logic to client applications
through various protocols
including HTTP.
A server that handles HTTP
protocol.

APPLICATION SERVER WEB SERVER
Job
Application server is used to
serve web based applications and
enterprise based applications(i.e
sevlets, jsps and ejbs...). because
application server contains web
server internally.
Web server is used to serve web
based applications.(i.e servlets
and jsps)
Functions
To deliver various applications to
another device, it allows
everyone in the network to run
software off of the same
machine.
Keeping HTML, PHP, ASP etc
files available for the web
browsers to view when a user
accesses the site on the web,
handles HTTP requests from
clients.
Examples of
popular server
products
Sun Java Application server,
weblogic server, Apache
Geronimo, IBM WebSphere
Application Server, Glass Fish
Server
Apache, Microsoft IIS, Tomcat,
Jetty
Clients can
include
GUIs, Web Servers Web browsers, search
enginerobots
Adds
Functionality?
Yes No, does not add any
functionality.

----------------------------------------------------------------------------------------
SELENIUM WEBDRIVER INTERVIEW QUESTIONS & ANWSER
Q 1. Can we create multiple instances with selenium web driver with same
Browser?
Ans: Yes, We can Create multiple Instances with selenium web driver.

ex: package Sample Package;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class Class1
{
public static void main(String[] args) throws InterruptedException
{
//Create 1st instance for IE
System.setProperty("webdriver.ie.driver", "C:\\Selenium
Automation\\IEDriverServer.exe");
InternetExplorerDriver ds1 = new InternetExplorerDriver();
ds1.get("http://google.co.in");
Thread.sleep(3000);
ds1.findElement(By.name("q")).sendKeys("software testing");
Thread.sleep(3000);
ds1.findElement(By.name("btnK")).click();
//Create 2nd instance for IE
System.setProperty("webdriver.ie.driver", "C:\\Selenium
Automation\\IEDriverServer.exe");
InternetExplorerDriver ds2 = new InternetExplorerDriver();
ds2.get("http://www.flipkart.com/");
Thread.sleep(3000);
ds2.findElement(By.name("q")).sendKeys("Computers");
Thread.sleep(3000);
//Create 3rd instance for IE
System.setProperty("webdriver.ie.driver", "C:\\Selenium
Automation\\IEDriverServer.exe");
InternetExplorerDriver ds3 = new InternetExplorerDriver();
ds3.get("http://google.co.in");
Thread.sleep(3000);
ds3.findElement(By.name("q")).sendKeys("software testing");
Thread.sleep(3000);

Note: Create number of instances but once we run the program it will
finish the 1st instance and 2nd instance then 3rd instance . it will not
open multiple browsers at a time

Q2. How can we run my application on to different browesrs ?
Ans: By Creating different instances with different browser.

package SamplePackage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

import BackUpprograms.webdriver_Reg;

public class Class1 {

public static void main(String[] args) throws InterruptedException
{
// Create an Instance for IE browser
System.setProperty("webdriver.ie.driver", "C:\\Selenium
Automation\\IEDriverServer.exe");
InternetExplorerDriver ds1 = new InternetExplorerDriver();
ds1.get("http://google.co.in");
Thread.sleep(3000);
ds1.findElement(By.name("q")).sendKeys("software testing");
Thread.sleep(3000);
ds1.findElement(By.name("btnK")).click();

// Create an Instance for Firefox browser
WebDriver ds = new FirefoxDriver();
ds.get("http://google.co.in");
Thread.sleep(3000);
ds.findElement(By.name("q")).sendKeys("software testing");

}
}


----------------------------------------------------------------------------------------
3. What is the difference between Xpath and dom?
DOM: The Document Object Model (DOM) is a cross-platform and language-independent convention for
representing and interacting withobjects in HTML, XHTML and XML documents. Objects in the DOM tree
may be addressed and manipulated by using methods on the objects
Ex: var element=document.getElementById("intro");

XPTAH: XPath, the XML Path Language, is a query language for selecting nodes from
an XML document. In addition, XPath may be used to compute values (e.g., strings, numbers,
or Boolean values) from the content of an XML document.
Ex: //input[@id=xxx]

----------------------------------------------------------------------------------------
SELENIUM WEBDRIVER INTERVIEW QUESTIONS ---PART 2
PART 2 SELENIUM WEBDRIVER INTERVIEW QUESTIONS WITH
ANSWERS
1. What is webdriver?
WebDriver is a simpler, more concise programming interface in addition to addressing some limitations
in the Selenium-RC API. Selenium-WebDriver was developed to better support dynamic web pages
where elements of a page may change without the page itself being reloaded. WebDrivers goal is to
supply a well-designed object-oriented API that provides improved support for modern advanced web-app
testing problems.
2. What are the advantages of selenium2.0/webdriver?
Need no server to start
Easy to code
Has sophisticated API to support wide verity of browsers.
Supports to test dynamic UI web apps.

3. Difference between the selenium1.0 and selenium 2.0?
Selenium 1.0 Selenium 2.0/Webdriver
1. It injected javascript functions into the
browser when the browser was loaded and
then used its javascript to drive the AUT
within the browser.

2. Selenium server need to start to run
tests
3. Has some loop-holes in supporting
complex UI apps,Javascript security
4. No support for headless broswers
1. WebDriver makes direct calls to the
browser using each browsers native
support for automation


2. Not needed unless tests are run on
local machine.
3. Supports even drag and drop features and
no security loop-holes
4. Supports htmlunit driver headless
browser runs fast


4. What are the Locators are there in selenium 2.0?
It supports locators based on Id,name,xpath,dom,css,class,tagname
5. How to handle the Ajax Applications in Web driver?
There are 2 types of waits webdriver supports to handle ajax applications to make webdrive sync to
execution:
Implicit wait :
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
Explicit wait: WebDriverWait, FluentWait
WebElement strr = (new
WebDriverWait(driver,30)).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[starts-
with(@id,'yui_3_4_0_1_137509')]/ul/li[2]/a")));
This link explains better about handling ajax in webdriver.
http://qeworks.com/handle-ajax-call-selenium-webdriver/

5. How to handle the multiple windows in web driver?
driver.switchTo().window(Window ID);

6. Difference between findelement() and findelements()?
findELement will find the first matching element.

findELements will all the matching elements. You'll probably need to loop through all the
elements returned.
7. How to handle the alerts in web driver?
driver.switchTo().alert().accept();

8. How to take the screen shots in seelnium2.0?
File src2 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src2,new File("d:\\sc2.jpeg"));
9. What is web driver architecture?
Below link gives better idea of webdriver architecture:
http://www.aosabook.org/en/selenium.html
10. What is the limitations of web driver?
Can not automate desktop applications, supports only web applications
No inbuilt commands to generate good reports
Cannot support readily for new browsers

----------------------------------------------------------------------------------------
How to capture bitmaps in Selenium? | Selenium
28 May 2012 0 comments
Bitmaps are captured using the Selenium set of commands. There are
two modes of capturing the bitmaps
1) Capture the bitmap for the entire page - it captures the browser main
page area of AUT
2) Capture the bitmap for the screen shots - it captures the entire screen
shot like the print screen that you give from your keyboard
Selenium doesn't support bitmap capturing for an element on AUT.
Read More!
When to use Accessors in Selenium? | Selenium
0 comments
Accessors are mostly used for storing the value in a variable.
The variable can be used for following reasons:
1) To get the value from an element and comparing with some dynamic
value
2) To take a logical decision to execute the test steps
ex: if the value of the variable true execute step1 and step2 else step3
and step4
3) To execute some statements in a loop based on the value returned by
the element.
Read More!
When to use Assert, Verify and WaitFor in Selenium? |
Selenium
0 comments
1) assert - If the expected value is mandatory to continue with the next
set of steps we will use Assert. As Assert aborts the test, if the expected
value doesn't match. It is good to use for any mandatory checks.
2) verify - If the expected value is optional to continue with the next set
of steps we will use Verify. As Verify continues executing with the next
set of steps, if the expected value doesn't match. It is good to use for any
optional checks.
3) waitFor - If your test needs to wait, if the expected value is not
matching we use waitFor. We normally use waitFor for AJAX kind of
controls loading within a page.
Read More!
What are the types of Assertions there in Selenium? |
Selenium
0 comments
Selenium Assertions can be used in 3 modes:
1) assert - When an assert fails, the test will be aborted. If you are
executing test suite, the next state case will start
2) verify - When a verify fails, the test will continue execution, logging
the failure.
3) waitFor - waitFor commands wait for some condition to become
true (which can be useful for testing Ajax applications). They will succeed
immediately if the condition is already true. However, they will fail and
halt the test if the condition does not become true within the current
timeout setting.
Read More!
What is Assertion in Selenium? | Selenium
0 comments
Assertion is nothing but a check or verification point.
Assertion verifies the state of the application conforms to what is
expected.
Examples include make sure the page title is X and verify that this
checkbox is checked.
Read More!
What is Selenese? | Selenium
0 comments
Selenium set of commands which are used for running the test are called
as Selenese.
There are three types of Selenese, those are:
1. Actions - used for performing the operations and interactions with the
target elements
2. Assertions - used as check points
3. Accessors - used for storing the values in a variable.
Read More!
How to use regular expressions in Selenium? | Selenium
0 comments
Regular expressions in Selenium IDE can be used with the keyword -
regexp: as a prefix to the value and patterns needs to be included for the
expected values.
For example if you want to use the regular expression for a command
Command: verifyText
Target: //font/font/b/font[1]
Value: Flight Confirmation # 2011-05-02451
in the above example Flight Confirmation is continuously changing each
time you run the test case. So this can be written with a regular
expression as mentioned below
Command: verifyText
Target: //font/font/b/font[1]
Value: regexp:Flight Confirmation # [0-9]{4}-[0-9]{2}-[0-9]{5,10}.
Read More!
What are the types of text patterns available in
Selenium? | Selenium
0 comments
There are three types of patterns available in Selenium:
1. globbing
2. regular expressions
3. exact.
Read More!
Does Selenium support Google Android Operating
System? | Selenium
0 comments
Yes, Selenium Web Driver or Google Web Driver or Selenium 2.0 supports
Android Operating System. There are several libraries written to support
Android Operating System.
Read More!
Does Selenium support mobile internet testing? |
Selenium
0 comments
Selenium supports Opera. And opera is used in most of the Smart
phones. So whichever Smart phone supports opera, selenium can be
used to test. So, one can use Selenium RC to run the tests on mobiles.
Read More!
What is the architecture of Selenium Grid? | Selenium
0 comments
The below mentioned theory explains about the setup of Selenium Grid
with architecture and how it works.
Selenium Grid builds on the traditional Selenium setup, taking advantage
of the following properties:
* The Selenium test, the application under test, and the remote
control/browser pair do not have to be co-located. They communicate
through HTTP, so they can all live on different machines.
* The Selenium tests and the web application under test are obviously
specific to a particular project. Nevertheless, neither the Selenium remote
control nor the browser is tied to a specific application. As a matter of
fact, they provide a capacity that can easily be shared by multiple
applications and multiple projects.
Consequently, if only we could build a distributed grid of Selenium
Remote Controls, we could easily share it across builds, applications,
projects - even potentially across organizations. Of course we would also
need to address the scalability issues as described earlier when covering
the traditional Selenium setup. This is why we need a component in
charge of:
* Allocating a Selenium Remote Control to a specific test (transparently)
* Limiting the number of concurrent test runs on each Remote Control
* Shielding the tests from the actual grid infrastructure
Selenium Grid calls this component the Selenium Hub.
* The Hub exposes an external interface that is exactly the same as the
one of a traditional Remote Control. This means that a test suite can
transparently target a regular Remote Control or a Selenium Hub with no
code change. It just needs to target a different IP address. This is
important as it shields the tests from the grid infrastructure (which you
can scale transparently). This also makes the developers life easier. The
same test can be run locally on a developer machine, or run on a heavy
duty distributed grid as part of a build without ever changing a line of
code.
* The Hub allocates Selenium Remote Controls to each test. The Hub is
also in charge of routing the Selenese requests from the tests to the
appropriate Remote Control as well as keeping track of testing sessions.
* When a new test starts, the Hub puts its first request on hold if there is
no available Remote Control in the grid providing the appropriate
capabilities. As soon as a suitable Remote Control becomes available, the
Hub will serve the request. For the whole time, the tests do not have to
be aware of what is happening within the grid; it is just waiting for an
HTTP response to come back.


Read More!
What is the architecture of Selenium RC? | Selenium
0 comments
The Selenium Server which launches and kills browsers, and acts as an
HTTP proxy for browser requests.
Client libraries for various programming languages, each of which
instructs the Selenium Server in how to test the AUT by passing it your
test scripts Selenium commands.
The diagram shows the client libraries communicate with the Server
passing each Selenium command for execution. Then the server passes
the Selenium command to the browser using Selenium-Core JavaScript
commands. The browser, using its JavaScript interpreter, executes the
Selenium command, which effectively, runs the check you specified in
your Selenese test script.
Read More!
What are the capabilities of Selenium WebDriver or
Google WebDriver or Selenium 2.0? | Selenium
0 comments
One should use WebDriver when requiring improved support for
Mult-browser testing including improved functionality for browsers not
well-supported by Selenium-1.0.
Handling multiple frames, multiple browser windows, popups, and
alerts.
Page navigation.
Drag-and-drop.
AJAX-based UI elements.
Read More!
What is Selenium WebDriver or Google WebDriver or
Selenium 2.0? | Selenium
0 comments
WebDriver uses a different underlying framework from Seleniums
javascript Selenium-Core. It also provides an alternative API with
functionality not supported in Selenium-RC. WebDriver does not depend
on a javascript core embedded within the browser, therefore it is able to
avoid some long-running Selenium limitations.
WebDrivers goal is to provide an API that establishes
A well-designed standard programming interface for web-app testing.
Improved consistency between browsers.
Additional functionality addressing testing problems not well-supported
in Selenium 1.0.
The Selenium developers strive to continuously improve Selenium.
Integrating WebDriver is another step in that process. The developers of
Selenium and of WebDriver felt they could make significant gains for the
Open Source test automation community be combining forces and
merging their ideas and technologies. Integrating WebDriver into
Selenium is the current result of those efforts.
Read More!
Which are the languages supported by Selenium RC? |
Selenium
0 comments
The languages supported by Selenium RC
1. .Net,
2. Java (Junt 3, Junt 4, TestNG, Groovy)
3. Perl,
4. Python,
5. PHP,
6. Ruby.
Read More!
Why Selenium RC is used? | Selenium
0 comments
Selenium-IDE does not directly support:
1. condition statements
2. iteration
3. logging and reporting of test results
4. error handling, particularly unexpected errors
5. database testing
6. test case grouping
7. re-execution of failed tests
8. test case dependency
9. capture screenshots on test failures
The reason behind why Selenium-IDE does not support the above
mentioned requirements is IDE supports only HTML language. Using
HTML language we cannot achieve the above mentioned requirements.
Because HTML does not support conditional, looping and external source
connectives.
To overcome the above mentioned problems Selenium RC is used.
Since Selenium RC supports the languages .Net, Java, Perl, Python, PHP,
and Ruby. In these languages we can write the programme to achieve
the IDE issues
Read More!
What is Selenium RC? | Selenium
0 comments
Selenium-RC is the solution for tests that need a little more than just
simple browser actions and a linear execution. Selenium-RC leverages the
full power of programming languages, creating tests that can do things
like read and write external files, make queries to a database, send
emails with test reports, and practically anything else a user can do with
a normal application.
You will want to use Selenium-RC whenever your test requires logic not
supported by running a script from Selenium-IDE
Read More!
Which are the Operating Systems supported by
Selenium? | Selenium
0 comments
Selenium IDE
Works in Firefox 2+ Start browser, run tests Run tests
Operating Systems Supported:
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others whichever supports Firefox 2+
Selenium Remote Control
Used for starting browser and run tests
Operating Systems Supported:
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others
Selenium Core
Used for running tests
Operating Systems Supported:
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others
Read More!
Which are the browsers supported by Selenium RC? |
Selenium
0 comments
Supported browsers for Selenium RC include:
1. *firefox
2. *mock
3. *firefoxproxy
4. *pifirefox
5. *chrome
6. *iexploreproxy
7. *iexplore
8. *firefox3
9. *safariproxy
10. *googlechrome
11. *konqueror
12. *firefox2
13. *safari
14. *piiexplore
15. *firefoxchrome
16. *opera
17. *iehta
18. *custom
Note: Any third party browser is supported with *custom followed by the
complete path of the browser with executable
Read More!
Which is the command used for displaying the values of a
variable into the output console or log? | Selenium
0 comments
The command used for displaying the values of a variable into the output
console or log - echo
If you want to display a constant string. The below mentioned command
can be used
echo <constant string>
ex: echo "The sample message"
If you want to display the value of a variable it can be written like below
echo ${<variable name>>
ex: echo ${var1}
Note: Here var1 is the variable.
Read More!
How to export the tests from Selenium IDE to Selenium
RC in different languages? | Selenium
0 comments
From selenium IDE the test cases can be exported into the
languages:
1. .Net,
2. Java,
3. Perl,
4. Python,
5. PHP,
6. Ruby
The below mentioned steps can explain how to export the test
cases:
1. Open the test case from Selenium IDE
2. Select File -> Export Test Case As
Read More!
How to debug the tests in Selenium IDE? | Selenium
0 comments
To debug or execute the test cases line by line. Follow the below
mentioned steps
1. Insert a break point (see the question to know more How to insert a
break point in Selenium IDE? )from the location where you want to
execute step by step
2. Run the test case
3. execution will be paused at the given break point
4. Click on the step (Blue) button to continue with the next statement
5. Click on Run button, to continue executing all the commands at a time.
Read More!
How to insert a break point in Selenium IDE? | Selenium
0 comments
Break point can be set in two ways in Selenium IDE:
1. Right click on the command in Selenium IDE and select "Toggle Break
Point"
2. Select the command in Selenium IDE and press "B" key on the
keyboard
3. If you want to clear the break point once again Spress "B" key on the
keyboard
4. You can set multiple break points in Selenium IDE.
Read More!
How to insert a comment in Selenium IDE? | Selenium
0 comments
Comments in Selenium IDE can be set in two ways
1. Right click on the command in Selenium IDE and select "Inert New
Comment"
2. If you want to comment an existing line. You need to follow the below
mentioned steps.
a. Select the source tab in IDE
b. Select the line which you want to comment
c. Assume that if you want to comment a open command you need to
write like below mentioned code
<tr>
<!--
<td>open&l/td>
<td>/node/304/edit&l/td>
<td></td>
-->
</tr>
Read More!
How to insert a start point in Selenium IDE? | Selenium
0 comments
Start point Selenium IDE can be set in two ways:
1. Right click on the command in Selenium IDE and select "Set / Clear
Start Point"
2. Select the command in Selenium IDE and press "S" key on the
keyboard
3. You can have only one start point
4. If you have already set one start point and you selected other
command as start point. Then the first start point will be removed and
the new start point will be set.
Read More!
How to execute a single line command from Selenium
IDE? Selenium
0 comments
Single line command from Selenium IDE can be executed in two
ways
1. Right click on the command in Selenium IDE and select "Execute This
Command"
2. Select the command in Selenium IDE and press "X" key on the
keyboard.
Read More!
Which are the browsers supported by Selenium IDE? |
Selenium
0 comments
Selenium IDE supports only one browser Mozilla Firefox.
The versions supported as of now are:
Mozilla Firefox 2.x
Mozilla Firefox 3.x
The versions not supported as of now are:
earlier versions of Mozilla Firefox 2.x
Mozilla Firefox 4.x.
Read More!
What are the challenges with Selenium IDE? | Selenium
0 comments
Selenium-IDE does not directly support:
1. condition statements
2. iteration or looping
3. logging and reporting of test results
4. error handling, particularly unexpected errors
5. database testing
6. test case grouping
7. re-execution of failed tests
8. test case dependency
9. capture screenshots on test failures
10. Results Report generations.
Read More!
What are the capabilities of Selenium IDE? | Selenium
0 comments
Selenium IDE (Integrated Development Environment) works similar to
commercial tools like QTP, Silk Test and Test Partner etc.
The below mentioned points describes well about Selenium IDE.
1. Selenium IDE is a Firefox add-on.
2. Selenium IDE can support recording the clicks, typing, and other
actions to make a test cases.
3. Using Selenium IDE A Tester can play back the test cases in the
Firefox browser
4. Selenium IDE supports exporting the test cases and suites to Selenium
RC.
5. Debugging of the test cases with step-by-step can be done
6. breakpoint insertion is possible
7. Page abstraction functionality is supported by Selenium IDE
8. Selenium IDE can supports an extensibility capability allowing the use
of add-ons or user extensions that expand the functionality of Selenium
IDE.
Read More!
What are the test types supported by Selenium? |
Selenium
0 comments
Selenium could be used for testing the web based applications.
The test types can be supported are:
1. functional,
2. regression,
3. load testing
The automation tool could be implemented for post release
validation with continuous integration tools like:
1. Jenkins,
2. Hudson,
3. QuickBuild
4. CruiseCont
Read More!
What are the technical challenges with selenium? |
Selenium
0 comments
As you know Selenium is a free ware open source testing tool.
There are many challenges with Selenium.
1. Selenium Supports only web based applications
2. It doesnt support any non web based (Like Win 32, Java Applet, Java
Swing, .Net Client Server etc) applications
3. When you compare selenium with QTP, Silk Test, Test Partner and
RFT, there are many challenges in terms of maintainability of the test
cases
4. Since Selenium is a freeware tool, there is no direct support if one is in
trouble with the support of applications
5. There is no object repository concept in Selenium, so maintainability of
the objects is very high
6. There are many challenges if one have to interact with Win 32 windows
even when you are working with Web based applications
7. Bitmap comparison is not supported by Selenium
8. Any reporting related capabilities, you need to depend on third party
tools
9. You need to learn any one of the native language like (.Net, Java, Perl,
Python, PHP, Ruby) to work efficiently with the scripting side of selenium.
Read More!
What do you know about Selenium? | selenium
0 comments
Selenium is a suite of tools for web automation testing.
Selenium first came to life in 2004 when Jason Huggins was testing an
internal application at ThoughtWorks.
Selenium was a tremendous tool, it wasnt without its drawbacks.
Because of its Javascript based automation engine and the security
limitations browsers apply to Javascript, different things became
impossible to do.
Selenium Suite of projects include:
Selenium IDE
Selenium Core
Selenium 1 (known as. Selenium RC or Remote Control)
Selenium 2 (known as. Selenium Webdriver)
Selenium-Grid.
Read More!
What is difference between QTP and Selenium? |
Selenium
0 comments
Only web applications can be testing using Selenium testing suite.
However, QTP can be used for testing client server applications. Selenium
supports following web browsers: Internet Explorer, Firefox, Safari, Opera
or Konqueror on Windows, Mac OS X and Linux. However, QTP is limited
to Internet Explorer on Windows.

QTP uses scripting language implemented on top of VB Script. However,
Selenium test suite has the flexibility to use many languages like Java,
.Net, Perl, PHP, Python, and Ruby.
Read More!
What are the advantages and disadvantages of using
Selenium as testing tool? | Selenium
0 comments
Advantages: Free, Simple and powerful DOM (document object model)
level testing, can be used for continuous integration; great fit with Agile
projects.
Disadvantages: Tricky setup; dreary errors diagnosis; can not test client
server applications.
Read More!
What programming languages can you use in Selenium
RC? | Selenium
0 comments
C#, Java, Perl, PHP, Python, Ruby.
Read More!
What browsers are supported by Selenium Remote
Control? | selenium
0 comments
The test automation expert can use Firefox, IE 7/8, Safari and Opera
browsers to run tests in Selenium Remote Control.


Read More!
What is the cost of Selenium test suite? selenium
0 comments
Selenium test suite a set of open source software tool, it is free of cost.
Read More!
What test can Selenium do? | Selenium
0 comments
Selenium is basically used for the functional testing of web based
applications. It can be used for testing in the continuous integration
environment. It is also useful for agile testing
Read More!
What you say about the flexibility of Selenium test suite?
| Selenium
0 comments
Selenium testing suite is highly flexible. There are multiple ways to add
functionality to Selenium framework to customize test automation. As
compared to other test automation tools, it is Seleniums strongest
characteristic. Selenium Remote Control support for multiple
programming and scripting languages allows the test automation
engineer to build any logic they need into their automated testing and to
use a preferred programming or scripting language of ones choice. Also,
the Selenium testing suite is an open source project where code can be
modified and enhancements can be submitted for contribution.
Read More!
How Selenium Grid works? | Selenium
0 comments
Selenium Grid sent the tests to the hub. Then tests are redirected to an
available Selenium RC, which launch the browser and run the test. Thus,
it allows for running tests in parallel with the entire test suite.
Read More!
What is Selenium Grid? | Selenium
0 comments
Selenium Grid in the selenium testing suit allows the Selenium RC
solution to scale for test suites that must be run in multiple
environments. Selenium Grid can be used to run multiple instances of
Selenium RC on various operating system and browser configurations.
Read More!
What is Selenium RC (Remote Control)? | Selenium
0 comments
Selenium RC allows the test automation expert to use a programming
language for maximum flexibility and extensibility in developing test
logic. For example, if the application under test returns a result set and
the automated test program needs to run tests on each element in the
result set, the iteration / loop support of programming languages can be
used to iterate through the result set, calling Selenium commands to run
tests on each item. Selenium RC provides an API and library for each of
its supported languages. This ability to use Selenium RC with a high level
programming language to develop test cases also allows the automated
testing to be integrated with the projects automated build environment.
Read More!
What are the disadvantage of Selenium IDE tool? |
Selenium
0 comments
1. Selenium IDE tool can only be used in Mozilla Firefox browser.
2. It is not playing multiple windows when we record it.


Read More!
What are the advantage and features of Selenium IDE? |
Selenium
0 comments
1. Intelligent field selection will use IDs, names, or XPath as needed
2. It is a record & playback tool and the script format can be written in
various languages including : C#, Java, PERL, Python, PHP, HTML
3. Auto complete for all common Selenium commands
4. Debug and set breakpoints
5. Option to automatically assert the title of every page
6. Support for Selenium user-extensions.js file.
Read More!
Can tests recorded using Selenium IDE be run in other
browsers? | Selenium
0 comments
Yes. Although Selenium IDE is a Firefox add on, however, tests created
in it can also be run in other browsers by using Selenium RC (Selenium
Remote Control) and specifying the name of the test suite in command
line.
Read More!
What is the use of context menu in Selenium IDE? |
Selenium
0 comments
It allows the user to pick from a list of assertions and verifications for the
selected location.
Read More!
What is Selenium IDE? | Selenium
0 comments
Selenium IDE is for building Selenium test cases. It operates as a Mozilla
Firefox add on and provides an easy to use interface for developing and
running individual test cases or entire test suites. Selenium-IDE has a
recording feature, which will keep account of user actions as they are
performed and store them as a reusable script to play back.
Read More!
What are the main components of Selenium testing
tools? | Selenium
0 comments
Selenium IDE, Selenium RC and Selenium Grid.
Read More!
What is Selenium? | Selenium
0 comments
Selenium is a set of tools that supports rapid development of test
automation scripts for web based applications. Selenium testing tools
provides a rich set of testing functions specifically designed to fulfil needs
of testing of a web based application.





http://java-success.blogspot.in/2011/10/jmeter-interview-questions-and-
answers.html

Q. What are some of the challenges you faced with JMeter?
If a subsequent request rely on the cookie set by the previous request,
the "cookie manager" element is required.



When setting up the "CSV Data Set Config", don't have any spaces in the
variable names.



What are Pre-Processor and Post-Processor elements? In what
order does JMeter process various type of elements?
A Pre-Processor executes some action prior to a Sampler Request being
made. If a Pre-Processor is attached to a Sampler element, then it will
execute just prior to that sampler element running. A Pre-Processor is
most often used to modify the settings of a Sample Request just before it
runs, or to update variables that aren't extracted from response text.

A Post-Processor executes some action after a Sampler Request has been
made. If a Post-Processor is attached to a Sampler element, then it will
execute just after that sampler element runs. A Post-Processor is most
often used to process the response data, often to extract values from it.

A Regular Expression Extractor can be used as a Post-Processor element
to extract values to be used elsewhere in subsequent requests. For
example, if you are using JSF and Seam frameworks, the jsfViewState
and CID values can be extracted as shown below:




The elements are executed in the following order as per the JMeter
documentation.

0. Configuration elements
1. Pre-Processors
2. Timers
3. Sampler
4. Post-Processors (unless SampleResult is null)
5. Assertions (unless SampleResult is null)
6. Listeners (unless SampleResult is null)

Timers, Assertions, Pre- and Post-Processors are only processed if there
is a sampler to which they apply. Logic Controllers and Samplers are
processed in the order in which they appear in the tree. Other test
elements are processed according to the scope in which they are found,
and the type of test element.

Q. How do you ensure re-usability in your JMeter scripts?
Using config elements like "CSV Data Set Config", "User Defined
Variables", etc for greater data reuse.
Modularizing shared tasks and invoking them via a "Module Controller".

Writing your own BeanShell functions, and reusing them.

----------------------------------------------------------------------------------------
1. Tell me something about your self/
2. What is the Difference between RC and Web Driver?
3. How to find the No. of Rows and Columns in a Web table?
4. How to get the no. of elements from a Drop down and Print the Elements
also?
5. Define your framework? How many folder in frame work?
6. I want to skip a Test in TestNg Test? how to skip same.
7. I want to get properties from xls , How to write script for the same?
8. Define DDL commands.
9. What is Inheritance?
10. what is Polymormisms?
11. What is Abstractions?
----------------------------------------------------------------------------------------
HOW TO WORK ON IE APPLICATIONS WITH SELENIUM WEB DRIVER
If you want to run your application on IE browser, there should be certain
configurations we need to do.

Please follow the below procedure.

1. Download "IESERVERDRIVER" from the below given path.
https://code.google.com/p/selenium/wiki/InternetExplorerDriver .

And make sure download the file according to your system configurations.
if it is windows 64 bit-- download :IEDriverServer_x64_2.37.0.zip
If it is windows 32 bit -- download : IEDriverServer_Win32_2.37.0.zip
After downloading the same . make sure unzip the file and ..
Create one folder in C: driver like below
C:\Selenium Automation\IEServerDriver ..
Now place the .exe file in the above path.

Now you need to do IE settings:

1. Open the IE browser.
2. Go to Tools option.
3. Go to Internet Options.
4. Select Security Tab.
Now.. Enable protected mode should be checked for
a. internet.
b. Local Intranet.
c.Trusted sites.
d. Restricted sites.



follow the below settings also


Now you can write the Program like below.


----------------------------------------------------------------------------------------
SELENIUM WEB DRIVER SCRIPTS
Selenium Web Driver Scripts:

1. FIND NO. OF ROWS AND COLUMNS IN A WEB TABLE.


package FAQs;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Totalrows {

public static void main(String[] args) throws Exception
{
//Create an instance for webdriver

WebDriver driver = new FirefoxDriver();
//Open the URL
driver.get("http://www.google.co.in");
//Maximize the browser
driver.manage().window().maximize();

try
{

// Finding No.of Rows in a web table

@SuppressWarnings("rawtypes")
List rows = driver.findElements(By.tagName("tr"));
System.out.println("There are "+ rows.size() + " Rows in a google page");
}
catch (Exception e)
{
System.out.println("error");
}

try
{
// Finding No.of Columns in a web table

@SuppressWarnings("rawtypes")
List Colms = driver.findElements(By.tagName("td"));
System.out.println("There are "+ Colms.size() + " Columns in a google page");
}
catch (Exception e)
{
System.out.println("error");
}
}

}


2. HOW TO UPLOAD FILE SCRIPT.


package FAQs;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class FileUpload {

public static void main(String[] args) throws InterruptedException {


String url ="http://www.2shared.com/";
System.setProperty("webdriver.ie.driver", "C:\\Selenium
Automation\\Ieserver\\IEDriverServer.exe");
// WebDriver driver = new FirefoxDriver();
WebDriver driver = new InternetExplorerDriver();
driver.get(url);
Thread.sleep(3000);

String filepath = "C:\\Users\\home\\Desktop\\test.txt";

driver.findElement(By.name("fff")).sendKeys(filepath);
System.out.println("Path of the file Entered Successfully");
Thread.sleep(3000);
// Click on UPload button
driver.findElement(By.xpath("//*[@id='overall']/tbody/tr[2]/td/form/input[3]")).click();

}

}

3. CONTEXT CLICK ON MENU.


package FAQs;


import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;

public class ContextClick
{

public static <E> void main(String[] args) throws InterruptedException
{
String url ="http://www.amazon.in/";
System.setProperty("webdriver.ie.driver", "C:\\Selenium
Automation\\Ieserver\\IEDriverServer.exe");
// WebDriver driver = new FirefoxDriver();
WebDriver driver = new InternetExplorerDriver();
driver.get(url);
Thread.sleep(3000);

driver.findElement(By.name("field-keywords")).sendKeys("laptops");
Thread.sleep(3000);
driver.findElement(By.name("field-keywords")).sendKeys(Keys.ARROW_DOWN);
Thread.sleep(3000);
driver.findElement(By.name("field-keywords")).sendKeys(Keys.ARROW_DOWN);
Thread.sleep(2000);
driver.findElement(By.name("field-keywords")).sendKeys(Keys.ARROW_DOWN);
Thread.sleep(2000);
driver.findElement(By.name("field-keywords")).sendKeys(Keys.ENTER);
Thread.sleep(2000);
WebElement parentEle =
driver.findElement(By.xpath("//*[@id='ref_1318473031']/li[2]/a/img"));

Actions Act = new Actions(driver);
Act.contextClick(parentEle).build().perform();
Thread.sleep(2000);
Act.sendKeys(Keys.ARROW_RIGHT).build().perform();
Thread.sleep(2000);
Act.sendKeys(Keys.ARROW_DOWN).build().perform();
Thread.sleep(2000);
Act.sendKeys(Keys.ARROW_DOWN).build().perform();
Thread.sleep(2000);
Act.sendKeys(Keys.ENTER).build().perform();

int siz = driver.findElements(By.xpath("//*[@id='sort']/option")).size();
System.out.println(siz);


Thread.sleep(2000);
// Handling multiple browsers
@SuppressWarnings("unchecked")
Set<E> Windowhandle = (Set<E>) driver.getWindowHandles();
Iterator<E> it = Windowhandle.iterator();

String Parentwin = (String) it.next();
String Childwin = (String) it.next();
Thread.sleep(2000);


Thread.sleep(2000);
driver.switchTo().window(Childwin);
Thread.sleep(2000);
driver.manage().window().maximize();
Thread.sleep(2000);
WebElement element = driver.findElement(By.xpath("//*[@id='sort']"));

Select dd= new Select(element);
dd.selectByIndex(2);
// dd.selectByValue("3");
// dd.selectByVisibleText("xyz");
Thread.sleep(2000);
// driver.close();
driver.switchTo().window(Parentwin);

}

}

4. HOW TO CREATE AN ACTIONS IN WEB DRIVER ( MOUSE OVER TO AN ELEMENT IN A WEB
PAGE)

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class FlipKart {


public static void main(String[] args) throws InterruptedException {
String url ="http://www.flipkart.com/";
WebDriver driver = new FirefoxDriver();
driver.get(url);
// Mouse Over to an Element in a Web Page
Actions Electronics = new Actions(driver);
Electronics.moveToElement(driver.findElement(By.linkText("ELECTRONICS"))).build().per
form();
Thread.sleep(3000);
driver.findElement(By.linkText("Samsung")).click();
}
}

5. HOW TO TAKE SCREEN SHOT IN WEB DRIVER

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.thoughtworks.selenium.ScreenshotListener;


public class ScreenShot
{


public static void main(String[] args) throws IOException

{

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy
somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

}

}

6. HOW TO FIND NO. OF ELEMENTS IN A DROP DOWN & LIST OF ELEMENTS TO
PRINT FROM DROP DOWN.

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class OptionsCoount {

public static void main(String[] args) throws InterruptedException {

String url ="http://www.flipkart.com/";
WebDriver driver1 = new FirefoxDriver();
driver1.get(url);
Actions Electronics = new Actions(driver1);
Electronics.moveToElement(driver1.findElement(By.linkText("ELECTRONI
CS"))).build().perform();
Thread.sleep(3000);
driver1.findElement(By.linkText("Samsung")).click();

Thread.sleep(3000);

// Finding No.of Items in a drop down

List<WebElement> Count =
driver1.findElements(By.xpath("//*[@id='sort-dropdown']/option"));
System.out.println("No. of elements in a drop down " +Count.size());
Thread.sleep(3000);

// Finding List Items in a drop down

List <WebElement> allSuggestions =
driver1.findElements(By.xpath("//*[@id='sort-dropdown']"));
for (WebElement suggestion : allSuggestions)
{

System.out.println("List of elements in a drop down with names "
+suggestion.getText());
}
}

}

----------------------------------------------------------------------------------------

Selenium Web Driver methods with Examples

1. Browser Back and Forward (NAVIGATION)
Steps to implement Browser back and forward through Selenium Web Driver
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Navigate to some page in website.
4. Use Selenium code to Navigate Back to Main Page.
CODE: driver.navigate().back();
driver.navigate().forward();
Example
WebDriver driver =new FirefoxDriver();
driver.get("http://seleniumhq.org/");
driver.findElement(By.linkText("Download")).click();
Thread.sleep(3000); //delay
driver.navigate().back();
driver.navigate().forward();
-------------------------------------------------------------------------------------------------------
-----------------------
2. Handling DRAG and DROP
Steps to Handle Drag and Drop through Selenium Web Driver
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Create an Action object for Driver
4. Fetch and create WebElement object for the SOURCE element.
5. Fetch and create WebElement object for the DESTINATION element.
6.Perform ACTION
1.Click and Hold the source WebElement
2.Move to destination WebElement
3.Release the Element.
Example
WebDriver driver = new FirefoxDriver();
driver.get("http://www.ericbieller.com/examples/dragdrop/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);
Actions act = new Actions(driver);
WebElement src = driver.findElement(By.xpath("//div[@id='items']/div[1]"));
WebElement des = driver.findElement(By.id("trash"));
act.clickAndHold(src).build().perform(); //For each action we need to build and Perform
act.moveToElement(des).build().perform();
act.release(des).build().perform();

-------------------------------------------------------------------------------------------------------
-----------------------
3. Making Single Select in Drop down (Option List)
Steps to make Single Select in Drop down through Selenium Web Driver. 1. Create Driver
for any Browser(Mozilla)
2. Go to the URL 3. Fetch the Drop Down element and create an object as WebElement. 4.
Create an Select object for the Drop Down Element object. 5. Create a List and collect all
Options through Select Object. 6. Create a Iterator object for the List. 7. Get the size of the
List. 8. Loop through and check for required element.
Example :
WebElement element = driver.findElement(By.name("selectedCustomer"));
Select dd= new Select(element);
List allOptions= dd.getOptions();
//To go through the list, we can use an Iterator. //Iterator should be of the same type as
the List //which is WebElement in this case.

Iterator it = allOptions.iterator();
//Using while loop, we can iterate till the List has //a next WebElement [hasNext() is true]
//number of items in the list

System.out.println(allOptions.size());
while(it.hasNext())
{
//When you say it.next(),
it points to a particular //WebElement in the List.
WebElement el = it.next();
//Check for the required element by Text and click it
if(el.getText().equals("mango"))
{
System.out.println(el.getAttribute("value"));
el.click();
} }
------------------------------------------------------------------------------------------------------------------------------
4.Making Single Select in Drop down (By INDEX, VALUE, TEXT)
Steps to make Single Select in Drop down through Selenium Web Driver.
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by INDEX
6. Select by VALUE
7. Select by VISIBLE TEXT
Example
WebElement customerdd =
driver.findElement(By.name("customerProject.shownCustomer"));
//convert the element to select object
Select cust = new Select(customerdd);
cust.selectByIndex(1); //Select by Index
Thread.sleep(3000); cust.selectByValue("2"); //Select by Value
Thread.sleep(3000);
cust.selectByVisibleText("mango"); //Select by Visible Text
----------------------------------------------------------------------------------------------------------------------------- -
5. Multiple Select List Box Window
Steps to make Multiple Select in Drop down through Selenium Web Driver.
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by Index(Start index)
6. Select by Index(End index)
Example
WebElement userdd = driver.findElement(By.name("users"));
Select usr = new Select(userdd);
usr.selectByIndex(0);
//Select by Index(From Start location)
usr.selectByIndex(2);
//Select by index(To End Location)
------------------------------------------------------------------------------------------------------------------------------
6. Multiple Select List Box Window - DESELECT
Steps to make Deselect in Drop down through Selenium Web Driver.
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by Index(Start index)
6. Select by Index(End index)
Example
WebElement userdd = driver.findElement(By.name("users"));
Select usr = new Select(userdd);
usr.selectByIndex(0);
usr.selectByIndex(2);
//You can deselect the options
usr.deselectAll();
//Deselect ALL selected elements //or
usr.deselectByIndex(0);
//Deselect By using Index //or
usr.deselectByValue(value);
//Deselect By using Value //or
usr.deselectByVisibleText(text); //Deselect By using Text
--------------------------------------------------
----------------------------------------------------------------------------
7. iFRAMES - How to handle Frames in Web Driver
Steps to get Source of each iFrame through Selenium Web Driver.
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Make a List containing FRAME web elements of a Web Page.
4. Get the Size of Frames.
5. Loop though and print the Source of each Frame
Example /*times of india website - multiple frames*/

driver.get("http://timesofindia.indiatimes.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
List frms= driver.findElements(By.tagName("iframe"));
//Frame List
System.out.println(frms.size());
for(int i=0;i
{
System.out.println(frms.get(i).getAttribute("src"));

}
------------------------------------------------------------------------------------------------------------------ ------------
8. iFRAMES - How to perform action in Frames
Steps to perform Action in iFrame through Selenium Web Driver.
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch iFrame element and create an Web Element object.
4. Using iFrame Web Element object, switch to IFrame.
5. Perform SendKeys/ Click action in iFrame.

Example
WebElement ifr = driver.findElement(By.xpath("//iframe[@src='/poll.cms']"));
driver.switchTo().frame(ifr);
//Switch to iFrame
driver.findElement(By.id("mathuserans2")).sendKeys("8");
//Perform Action in iFrame
----------------------------------------------------------------------------------------------------------------------------- -
9.iFRAMES - How to switch to a perticular Frame through index
Steps to switch to perticular iFrame by index through Selenium Web Driver.
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Make a List containing FRAME web elements of a Web Page.
4. Get the Size of Frames.
5. Switch to required iFrame through index.
Example
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
List frms= driver.findElements(By.tagName("iframe"));
System.out.println(frms.size()); driver.switchTo().frame(0);
driver.findElement(By.id("clicktripad")).click();
------------------------------------------------------------------------------------------------------------------------------
10. TABS / New Window
When Browser opens in a new window or in a new tab, Web Driver cannot shift the control
to the new Window/ Tab. We need to collect the window handles in a page. Whenever a new
window opens we need to iterate and shift to the latest window handle. TABS/New Window -
1 Steps to iterate through the Window Handles
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Collect Window Handles through Set
4. Create an iterator to iterate through Window Handles.
5. At First iterator will not be pointing to any Window Handle, only First increment Points to
First Window Handle, Second increment Points to second iterator.

Set windowHandles = driver.getWindowHandles();

Iterator it = windowHandles.iterator();

while(it.hasNext())
{
System.out.println(it.next());

}
--------------------------------------------------------------------------------------------------------------- ---------------

TABS/New Window - 2 When two browsers are opened and Web Driver need to shift the
control from Parent Window to Child Window. Please follow the steps mentioned below.
1. Create Driver for any Browser(Mozilla)
2. Go to the URL 3. Collect Window Handles through Set
4. Create an iterator to iterate through Window Handles.
5. Increment the iterator and store the Window Handle as Parent.
6. Increment the iterator and store next Window Handle as Child.
7. Switch to Child Browser using Child Window Handle.

Set windowHandles = driver.getWindowHandles();
Iterator it = windowHandles.iterator();
String parentBrowser= it.next();
String childBrowser = it.next();
driver.switchTo().window(childBrowser);

------------------------------------------------------------------------------------------------------------------------------
TABS/New Window - 3
When second browser is closed/you close it and Web Driver need to shift the control from
Child Window to Parent Window. Please follow the steps mentioned below.
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Collect Window Handles through Set
4. Create an iterator to iterate through Window Handles.
5. Increment the iterator and store the Window Handle as Parent.
6. Increment the iterator and store next Window Handle as Child.
7. Switch to Child Browser using Child Window Handle. 8. When Child browser get closed,
Switch from Child browser to Parent Window.
Set windowHandles = driver.getWindowHandles();
Iterator it = windowHandles.iterator();
String parentBrowser= it.next();
String childBrowser = it.next();
driver.switchTo().window(childBrowser);
Thread.sleep(3000); driver.close(); //close the current window(Child Browser)
driver.switchTo().window(parentBrowser); //Switch to Parent Browser
----------------------------------------------------------------------------------------------------------------------------- -
11. CALENDAR popups Calendar PopUp - 1

Normal Calender(current month) Popup can be handled in the following way.
1. Create Driver for any Browser(Mozilla)
2. Go to the URL 3. Fetch the Calender element and click to open.
4. Fetch the required date through xpath and click. /*IRCTC calendar*/

driver.findElement(By.id("calendar_icon1")).click();
driver.findElement(By.xpath("//div[@id='CalendarControl']/table[tbody[tr[td[text()='Octobe
r 2012']]]]/descendant::a[text()='5']")).click();
----------------------------------------------------------------------------------------------------------------------------- -
Calendar PopUp - 2 (Customized wait)

In a Calender if we want to click on future month which is not currently displayed, we need
to click on next link until we get the required month. This can be done by writing
Customized wait. Check for particular date element in each month, if not found move to
next month. /*makemytrip calendar*/


driver.get("http://www.makemytrip.com/");

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

driver.findElement(By.id("deptDateRtripimgExact")).click();
//find Calendar
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

boolean flag=true;
while(flag)
{ try

{
WebElement el = driver.findElement(By.xpath("//div[contains(@class,'ui-datepicker-group')

and descendant::span[text()='March']]/descendant::a[text()='5']")); // Required future
date

if(el !=null) //Check if the required date element is found or not

{

el.click();

// if required Date is found, then click the date

flag=false;
}
} catch (Exception e)
{ //Catches exception if no element found try
{
Thread.sleep(500);

driver.findElement(By.xpath("//a[@title='Next']")).click();
//Click on next month

} catch (InterruptedException e1)

{ // TODO Auto-generated catch block
e1.printStackTrace();
}
}

}
------------------------------------------------------------------------------------------------------------------------------
12. Drop Down MENU
In order to click on an menu item, first we need to move the mouse over Parent menu, later
we can click on any of the Menu child item. Please follow the steps mentioned below.
1. Create Driver for any Browser(Mozilla)
2. Go to the URL 3. Fetch the MENU Parent element and create a WebElement object. 4.
Create an Action object for Driver 5. Through Action object, move to Parent element. 6.
Give a Delay for menu items to be displayed. 7. Fetch the Child item through xpath and
Click on it.
WebElement parentMenu = driver.findElement(By.linkText("Tourist Trains"));
Actions act = new Actions(driver); // Create an Action object //move to the parent menu
item
act.moveToElement(parentMenu).build().perform();
Thread.sleep(3000); //wait till the child items are displayed
driver.findElement(By.linkText("Bharat Tirth")).click();
------------------------------------------------------------------------------------------------------------------------------
13. Context Click (Right Click)
We can use keyboard keys to Make a Right Click.
Please follow the steps mentioned below.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL. 3. Fetch the MENU Parent element and create a WebElement object. 4.
Create an Action Object for Driver. 5. Through Action Object, make a Context Click on Menu
Parent object. 6. Through Action Object, send keys for
ARROW_DOWN/ARROW_UP/Keys.ENTER. Example WebElement parentMenu =
driver.findElement(By.linkText("Tourist Trains")); Actions act = new Actions(driver);
//Create Action object for Driver
act.contextClick(parentMenu).build().perform(); //Context Click
act.sendKeys(Keys.ARROW_RIGHT).build().perform(); Thread.sleep(1000);
act.sendKeys(Keys.ARROW_DOWN).build().perform(); Thread.sleep(1000);
act.sendKeys(Keys.ENTER).build().perform(); ----------------------------------------------------------------------
--------------------------------------------------------
14. JAVA SCRIPT example
We can use java script command to perform actions.
We can write code to fill up the text box through java script.
Please follow the steps mentioned below.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL. 3. Create Java Script executor object for the Driver. 4. Store the Java
Script command in a String Variable. 5. Java Script Executor object executes the command
in the Variable.
JavascriptExecutor js = (JavascriptExecutor) driver; String jsCmd =
"document.getElementsByName('city')[0].value='ban'"; js.executeScript(jsCmd); ---------------
---------------------------------------------------------------------------------------------------------------
15. Multiple Elements
We can count the number of links present in the page. We can also print the link text of
each Web link. Please follow the steps mentioned below.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL. 3. Fetch elements with tag //a in the entire page, store it in a List. 4. Get
the count of Links present in the Page. 5. Loop through the links and print the Attributes

List allLinks= driver.findElements(By.xpath("//a")); //display the count of links in the page
System.out.println(allLinks.size()); //display the text for each link on the page for(int i=0;i
{ //display href for each link System.out.println(allLinks.get(i).getAttribute("href"));

//display text for each link
System.out.println(allLinks.get(i).getText()); //perform click action
allLinks.get(i).click();
}
------------------------------------------------------------------------------------------------------------------------------ 16.
Other Browser (Internet Explorer)
Using Internet Explorer with Web Driver.
Please follow the steps mentioned below. 1. Set System Property for the Driver and give
path of the IE Driver. 2. Create an Web Driver Object. 3. Open an URL
System.setProperty("webdriver.ie.driver", "D:\\sel\\browserdrivers\\IEDriverServer.exe");
WebDriver driver =new InternetExplorerDriver(); driver.get("www.google.com"); ----------------
--------------------------------------------------------------------------------------------------------------
17. Other Browser (Chrome)
Using Chrome with Web Driver.
Please follow the steps mentioned below. 1. Set System Property for the Driver and give
path of the Chrome Driver. 2. Create an Web Driver Object. 3. Open an URL
System.setProperty("webdriver.chrome.driver",
"D:\\sel\\browserdrivers\\Chromedriver.exe"); WebDriver driver = new ChromeDriver();
driver.get("www.google.com"); --------------------------------------------------------------------------------------------
----------------------------------
18. PROXY settings.
Please follow the steps mentioned below.
1. Import Selenium.Proxy
2. Create a Profile object for Firefox
3. Create a string variable with value.
4. Create a Proxy object.
5. Set the values through proxy.
6. Set the proxy preference to proxy object using profile object.
7. Pass the profile object to Firefox Driver.
import org.openqa.Selenium.Proxy FirefoxProfile profile = new FirefoxProfile(); String
PROXY = "xx.xx.xx.xx:xx"; Proxy proxy = new Proxy(); proxy.HttpProxy=PROXY;
proxy.FtpProxy=PROXY; proxy.SslProxy=PROXY; profile.SetProxyPreferences(proxy);
FirefoxDriver driver = new FirefoxDriver(profile);
------------------------------------------------------------------------------------------------------------------------------
19. Page Onload authentication
Sometimes when you are Automating Web pages, you may come across Page onload
Authentication window. This window is not java popup/div. It is windows popup. Selenium
directly cannot handle this windows popup.
Hence we use Autoit sowftware tool. Through Selenium we can handle this situation using
Autoit.
Please follow the steps mentioned below.
1.Download Autoit from the following URl
( http://www.autoitscript.com/site/autoit/downloads/ )
2.Install downloaded software.
3. Open Script Editor
Start=>ProgramFiles=>AutoIt =>SciTE Script Editor.
4.Open Object Identifier.
Start=>ProgramFiles=>AutoIt =>AutoIt Window Info.
5.Drag and Drop finder tool in AutoIt Window Info, to the Window you need to identify.
6.Collect the Title Name of window from (AutoIt Window Info.)
7.Write the Script in the Editor.
----------------------------------------------------AUTOIT CODE-----------------------------------------------------
WinWaitActive("Authentication Required")
Send("admin")
Send("{TAB} admin{TAB} {ENTER}") ---------------------------------------------------------------------------------
---------------------------------------------
8.Save the file as default save.(Authentication1.exe)
9.RUN/Compile the SCRIPT, it creates an exe.
10.Mention the exe path in the Program before creation of Driver.
EXAMPLE: Process P = Runtime.getRuntime().exec("D:\\java_prj\\SELENIUM
WEBDRIVER\\AUTOIT\\Authentication1.exe"); WebDriver driver = new FirefoxDriver();
driver.get("http://192.168.1.1");
----------------------------------------------------------------------------------------------------------------------------- -
20. File Download
Please follow the steps mentioned below.
1. Create a PROFILE object of Browser. 2. Set Preference, by giving Download destination
Directory. 3. Set Preference, by giving Default Folder. 0 => Desktop, 1=>System Default
Location, 2 => Indicates a custom Folder Location 4. Set Preference, A comma-separated
list of MIME types to save to disk without asking what to use to open the file. Default value
is an empty string. After coding the above mentioned steps, now start the driver and click
on Download button/link. 1. Create Driver for any Browser(Mozilla).
2. Go to the URL. 3. Fetch the Download web element and click. FirefoxProfile Prof = new
FirefoxProfile(); Prof.setPreference("browser.download.dir", "D:\\java prj");
Prof.setPreference("browser.download.folderList", 2);
Prof.setPreference("browser.helperApps.neverAsk.saveToDisk","application/zip"); WebDriver
driver = new FirefoxDriver(Prof); driver.get("http://seleniumhq.org/download/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);
driver.findElement(By.xpath("//a[@name='client-
drivers']/table/tbody/tr[1]/td[4]/a")).click();
----------------------------------------------------------------------------------------------------------------------------- -



21. File Upload
Please follow the steps mentioned below. 1. Create Driver for any Browser(Mozilla).
2. Go to the URL. 3. Store the Source path of file in a variable.
4. Fetch the Upload web element text box and give path using variable. 5. Fetch the upload
button and click WebDriver driver = new FirefoxDriver();
driver.get("http://www.2shared.com/"); String FilePath =
"C:\\Users\\abc\\Desktop\\test.xml";
driver.findElement(By.id("upField")).sendKeys(FilePath);
driver.findElement(By.xpath("//input[@type='image']")).click();
------------------------------------------------------------------------------------------------------------------------------
22. Handling JAVA ALERT
Sometimes you may get alerts as anticipated(through Insert/update/delete operation in
database). These may be JAVA alerts. Please follow the steps mentioned below to handle
Alerts.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL. 3. You get an alert asking to click on 'YES' or 'NO' button. 4. First Confirm
if it is JAVA alert window. 5. Write a code to switch the control to Alert window. 6. In the
Alert window, either ACCEPT by clicking on 'YES' or CANCEL by clicking on 'NO'. WebDriver
driver = new FirefoxDriver(); driver.get("http://www.2shared.com/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES); Alert alert =
driver.switchTo().alert(); alert.accept(); //or alert.dismiss();

----------------------------------------------------------------------------------------
Please find the below important question & answers which will ask in interview for
Webdriver

Selenium WebDriver methods with Examples

1.Browser Back and Forward (NAVIGATION)

Steps to implement Browser back and forward through Selenium Web
Driver

1. Create Driver for any Browser(Mozilla)

2. Go to the URL

3. Navigate to some page in website.

4. Use Selenium code to Navigate Back to Main Page.

CODE: driver.navigate().back();

driver.navigate().forward();

Example

WebDriver driver =new FirefoxDriver();

driver.get("http://seleniumhq.org/");

driver.findElement(By.linkText("Download")).click();

Thread.sleep(3000); //delay

driver.navigate().back();

driver.navigate().forward();

----------------------------------------------------------------
--------------------------------------------------------------


2.Handling DRAG and DROP



Steps to Handle Drag and Drop through Selenium Web Driver



1. Create Driver for any Browser(Mozilla)

2. Go to the URL

3. Create an Action object for Driver

4. Fetch and create WebElement object for the SOURCE
element.

5. Fetch and create WebElement object for the DESTINATION
element.

6.Perform ACTION

1.Click and Hold the source WebElement

2.Move to destination WebElement

3.Release the Element.

Example


WebDriver driver = new FirefoxDriver();
driver.get("http://www.ericbieller.com/examples/dragdrop/
");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINU
TES);
Actions act = new Actions(driver);
WebElement src =
driver.findElement(By.xpath("//div[@id='items']/div[1]"))
;
WebElement des = driver.findElement(By.id("trash"));
act.clickAndHold(src).build().perform(); //For each
action we need to build
and Perform
act.moveToElement(des).build().perform();
act.release(des).build().perform();----------------------
---------------------------------------------------------
---
--------------------------------------------
3.HowtogetnumberoflinksinaWebpage.(Googlepage)

06 November 2013 19:09:36
package practice_webdriver;
02.import java.util.List;
03.
04.import java.util.concurrent.TimeUnit;
05.import org.openqa.selenium.*;
06.import org.openqa.selenium.firefox.FirefoxDriver;
07.import org.openqa.selenium.support.ui.ExpectedConditions;
08.import org.openqa.selenium.support.ui.WebDriverWait;
09.
10.public class AllLinks {
11.
12. public static void main(String[] args) {
13. String baseUrl = "http://newtours.demoaut.com/";
14. WebDriver driver = new FirefoxDriver();
15. String underConsTitle = "Under Construction: Mercury Tours";
16. driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
17.
18. driver.get(baseUrl);
19. List<WebElement> linkElements = driver.findElements(By.tagName("a"
));
20. String[] linkTexts = new String[linkElements.size()];
21. int i = 0;
22.
23. //extract the link texts of each link element
24. for (WebElement e : linkElements) {
25. linkTexts[i] = e.getText();
26. i++;
27. }
28.
29. //test each link
30. for (String t : linkTexts) {
31. driver.findElement(By.linkText(t)).click();
32. if (driver.getTitle().equals(underConsTitle)) {
33. System.out.println("\"" + t + "\""
34. + " is under construction.");
35. } else {
36. System.out.println("\"" + t + "\""
37. + " is working.");
38. }
39. driver.navigate().back();
40. }
41. driver.quit();
42. }

----------------------------------------------------------------------------------------
Introduction of TestNG framework -
Advantages of TestNG over Junit
framework
In Selenium WebDriver training tutorial we have seen how to run Selenium scripts
using JUnit framework. Until now we have execute selenium tests but we have not
generated reports in JUnit. In this Selenium training article series we are introducing
powerful new testing framework called TestNG. The TestNG framework means Next
Generation testing framework, so we are seeing what all next generation features available
in TestNG, also I will talk about advantages of TestNG over Junit. I will be discussing about
different ways of using TestNG features in my coming articles.
I do not say that dont use JUnit, but you should really consider using TestNG for your next
project. Apparently TestNG is more complete and clean than JUnit.

What is TestNG?
TestNG is testing framework inspired from most popular JUnit framework used for the Java
programming language. The TestNG framework is introduced to overcome the limitations of
JUnit framework. Most of the automation users are using this framework because of its
advantages & more supported features. Until we have executed selenium test script but not
even generated test reports. So using this TestNG framework we will learn how to generate
test reports.


Features of TestNG Framework:
TestNG supports many powerful features & it is easy to use. Lets see what all new features
are supported in new testing framework:
Support for parameters.
Supports dependent methods testing.
Test configuration flexible.
Supports powerful execution model.
Embeds BeanShell for further flexibility.
TestNG has a more elegant way of handling parameterized tests with the data-
provider concept.
For the same test class TestNG support for multiple instances.
Extendibility of using different Tools and plug-ins like Eclipse, Maven, IDEA etc.
Default JDK functions for runtime and logging (no dependencies).
Supported different Annotations like @BeforeSuite, @AfterSuite, @BeforeClass,
@AfterClass, @BeforeTest, @AfterTest, @BeforeGroups, @AfterGroups,
@BeforeMethod, @AfterMethod, @DataProvider, @Factory, @Listeners,
@Parameters, @Test.
TestNG supports annotations which are very helpful to guide test case executions. Similarly
in JUnit, the TestNG annotations are always preceded by the @ symbol. It permit you do
parallel execution of test cases & we can also skip the test cases effortlessly while executing
test cases.
TestNG is specially designed to cover all types testing categories like Unit, Functional
testing, Integration testing, End-to-end etc. Using TestNG framework allows us to generate
test reports in both HTML and XML formats. Using ANT with TestNG, we can generate
primitive Testng reports as well.

Advantages of TestNG over Junit:
1. In TestNG Annotations are easy to understand over JUnit.
2. In TestNG there is no constraint like you have to declare @BeforeClass and
@AfterClass, which is present in JUnit.
3. As method name constraint is present in JUnit, such method name constraint is not
present in TestNG and you can specify any test method names.
4. In TestNG enable you to grouping of test cases easily which is not possible in JUnit.
5. TestNG supports following three 3 additional setUp/tearDown level:
@Before/AfterSuite, @Before/AfterTest and @Before/AfterGroup.
6. TestNG do not require extend any class.
7. TestNG allows us to define the dependent test cases each test case is independent to
other test case.
8. TestNG allows us to execute of test cases based on group. Lets take a scenario
where we have created two set of groups Regression & Sanity. If we want to
execute the test cases under Sanity group then it is possible in TestNG framework.
9. Parallel execution of Selenium test cases is possible in TestNG.

Conclusion:
If you enjoy reading this article please make sure to share it with your friends. Please leave
your questions/tips/suggestions in the comment section below and Ill try to answer as
many as I can.
In Next article, we will see Steps to install TestNG in Eclipse.
You can also Subscribe by E-mail and get All New articles delivered directly to your Inbox.

----------------------------------------------------------------------------------------
DATA DRIVEN TESTING USING JAVA WEBDRIVER TESTNG FRAMEWORK
In this post I implemented that how to perform data driven testing using java
Webdriver TestNg framework. As we know testNg provide @DataProvider annotation,
using this I can pass a set of data into our Webdriver test method. I have created a sample
test script for Wikipedia where I use a set of country data, with Wikipedia search
functionality and verify searched country.
?
1
2
3
4
5
package com.test;

import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataDrivenTest {

private WebDriver driver;
private String baseUrl;

@DataProvider(name = "myTest")
public Object[][] createData1() {
return new Object[][] {
{ "India"},
{ "Brazil"},
{ "Canada"},
{ "Sri Lanka"},
{ "England"},
{ "UK"},
{ "United States"},
};
}

@BeforeMethod
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.wikipedia.org/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test(dataProvider = "myTest")
public void testSearchCountry(String country) throws Exception {
driver.get(baseUrl + "/wiki/Main_Page");
driver.findElement(By.id("searchInput")).clear();
driver.findElement(By.id("searchInput")).sendKeys(country);
driver.findElement(By.id("searchButton")).click();
String str = driver.findElement(By.cssSelector("span")).getText();
Assert.assertTrue(country.equals(str.trim()));
}

@AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
}
Above test script executed seven times for each set of data used in @DataProvider
annotation. Any failed test does not impact other set of execution.

After execution of above test script TestNg report should be generated as below:

Below are the execution log of above test:

PASSED: testSearchCountry("India")
PASSED: testSearchCountry("Brazil")
PASSED: testSearchCountry("Canada")
PASSED: testSearchCountry("Sri Lanka")
PASSED: testSearchCountry("England")
PASSED: testSearchCountry("United States")
FAILED: testSearchCountry("UK")

Above test failed for the value UK as searched result is United Kingdom not UK

Hope above test will help you for data driven testing. Comment here if you have any query.

----------------------------------------------------------------------------------------
Selenium WebDriver methods with Examples

1.BROWSER BACK AND FORWARD (NAVIGATION)
Steps to implement Browser back and forward through Selenium Web Driver
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Navigate to some page in website.
4. Use Selenium code to Navigate Back to Main Page.
CODE: driver.navigate().back();
driver.navigate().forward();
Example
WebDriver driver =new FirefoxDriver();
driver.get("http://seleniumhq.org/");
driver.findElement(By.linkText("Download")).click();
Thread.sleep(3000); //delay
driver.navigate().back();
driver.navigate().forward();
------------------------------------------------------------------------------------------------------------- -----------------
2.HANDLING DRAG AND DROP

Steps to Handle Drag and Drop through Selenium Web Driver

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Create an Action object for Driver
4. Fetch and create WebElement object for the SOURCE element.
5. Fetch and create WebElement object for the DESTINATION element.
6.Perform ACTION
1.Click and Hold the source WebElement
2.Move to destination WebElement
3.Release the Element.
Example

WebDriver driver = new FirefoxDriver();
driver.get("http://www.ericbieller.com/examples/dragdrop/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);

Actions act = new Actions(driver);
WebElement src = driver.findElement(By.xpath("//div[@id='items']/div[1]"));
WebElement des = driver.findElement(By.id("trash"));

act.clickAndHold(src).build().perform(); //For each action we need to build and
Perform
act.moveToElement(des).build().perform();
act.release(des).build().perform();---------------------------------------------------------------------------------------
---------------------------------------

3.MAKING SINGLE SELECT IN DROP DOWN (OPTION LIST)

Steps to make Single Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Create an Select object for the Drop Down Element object.
5. Create a List and collect all Options through Select Object.
6. Create a Iterator object for the List.
7. Get the size of the List.
8. Loop through and check for required element.

Example

WebElement element = driver.findElement(By.name("selectedCustomer"));
Select dd= new Select(element);
List allOptions= dd.getOptions();

//To go through the list, we can use an Iterator.
//Iterator should be of the same type as the List
//which is WebElement in this case.

Iterator it = allOptions.iterator();
//Using while loop, we can iterate till the List has
//a next WebElement [hasNext() is true]
//number of items in the list
System.out.println(allOptions.size());

while(it.hasNext()){
//When you say it.next(), it points to a particular
//WebElement in the List.
WebElement el = it.next();
//Check for the required element by Text and click it
if(el.getText().equals("mango")){
System.out.println(el.getAttribute("value"));
el.click();
}
}
----------------------------------------------------------------------------------------------------------------------------- -

4.MAKING SINGLE SELECT IN DROP DOWN (BY INDEX, VALUE, TEXT)
Steps to make Single Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by INDEX
6. Select by VALUE
7. Select by VISIBLE TEXT

Example

WebElement customerdd =
driver.findElement(By.name("customerProject.shownCustomer"));
//convert the element to select object
Select cust = new Select(customerdd);
cust.selectByIndex(1); //Select by Index
Thread.sleep(3000);
cust.selectByValue("2"); //Select by Value
Thread.sleep(3000);
cust.selectByVisibleText("mango"); //Select by Visible Text
----------------------------------------------------------------------------------------------------------------------------- -

5.MULTIPLE SELECT LIST BOX WINDOW
Steps to make Multiple Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by Index(Start index)
6. Select by Index(End index)

Example


WebElement userdd = driver.findElement(By.name("users"));
Select usr = new Select(userdd);
usr.selectByIndex(0); //Select by Index(From Start location)
usr.selectByIndex(2); //Select by index(To End Location)
----------------------------------------------------------------------------------------------------------------------------- -

6.MULTIPLE SELECT LIST BOX WINDOW - DESELECT
Steps to make Deselect in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by Index(Start index)
6. Select by Index(End index)

Example

WebElement userdd = driver.findElement(By.name("users"));
Select usr = new Select(userdd);
usr.selectByIndex(0);
usr.selectByIndex(2);



//You can deselect the options
usr.deselectAll(); //Deselect ALL selected elements
//or
usr.deselectByIndex(0); //Deselect By using Index
//or
usr.deselectByValue(value); //Deselect By using Value
//or
usr.deselectByVisibleText(text); //Deselect By using Text
----------------------------------------------------------------------------------------------------------------------------- -

7.IFRAMES - HOW TO HANDLE FRAMES IN WEB DRIVER
Steps to get Source of each iFrame through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Make a List containing FRAME web elements of a Web Page.
4. Get the Size of Frames.
5. Loop though and print the Source of each Frame

Example


/*times of india website - multiple frames*/

driver.get("http://timesofindia.indiatimes.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

List frms= driver.findElements(By.tagName("iframe")); //Frame List
System.out.println(frms.size());
for(int i=0;i
{
System.out.println(frms.get(i).getAttribute("src"));
}----------------------------------------------------------------------------------------------------------------------------- -

8.IFRAMES - HOW TO PERFORM ACTION IN FRAMES
Steps to perform Action in iFrame through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch iFrame element and create an Web Element object.
4. Using iFrame Web Element object, switch to IFrame.
5. Perform SendKeys/ Click action in iFrame.

Example

WebElement ifr = driver.findElement(By.xpath("//iframe[@src='/poll.cms']"));
driver.switchTo().frame(ifr); //Switch to iFrame
driver.findElement(By.id("mathuserans2")).sendKeys("8"); //Perform Action in iFrame
----------------------------------------------------------------------------------------------------------------------------- -

9.IFRAMES - HOW TO SWITCH TO A PERTICULAR FRAME THROUGH INDEX
Steps to switch to perticular iFrame by index through Selenium Web Driver.


1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Make a List containing FRAME web elements of a Web Page.
4. Get the Size of Frames.
5. Switch to required iFrame through index.


Example

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

List frms= driver.findElements(By.tagName("iframe"));
System.out.println(frms.size());
driver.switchTo().frame(0);
driver.findElement(By.id("clicktripad")).click();
----------------------------------------------------------------------------------------------------------------------------- -


10. TABS / NEW WINDOW

When Browser opens in a new window or in a new tab, Web Driver cannot shift the control
to the new Window/ Tab. We need to collect the window handles in a page. Whenever a new
window opens we need to iterate and shift to the latest window handle.

TABS/New Window - 1

Steps to iterate through the Window Handles

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Collect Window Handles through Set
4. Create an iterator to iterate through Window Handles.
5. At First iterator will not be pointing to any Window Handle, only First increment Points to
First Window Handle, Second increment Points to second iterator.


Set windowHandles = driver.getWindowHandles();
Iterator it = windowHandles.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}------------------------------------------------------------------------------------------------ ------------------------------

TABS/New Window - 2

When two browsers are opened and Web Driver need to shift the control from Parent
Window to Child Window.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Collect Window Handles through Set
4. Create an iterator to iterate through Window Handles.
5. Increment the iterator and store the Window Handle as Parent.
6. Increment the iterator and store next Window Handle as Child.
7. Switch to Child Browser using Child Window Handle.


Set windowHandles = driver.getWindowHandles();
Iterator it = windowHandles.iterator();


String parentBrowser= it.next();
String childBrowser = it.next();
driver.switchTo().window(childBrowser);
------------------------------------------------------------------------------------------------------------------------------

TABS/New Window - 3

When second browser is closed/you close it and Web Driver need to shift the control from
Child Window to Parent Window.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Collect Window Handles through Set
4. Create an iterator to iterate through Window Handles.
5. Increment the iterator and store the Window Handle as Parent.
6. Increment the iterator and store next Window Handle as Child.
7. Switch to Child Browser using Child Window Handle.
8. When Child browser get closed, Switch from Child browser to Parent Window.


Set windowHandles = driver.getWindowHandles();
Iterator it = windowHandles.iterator();

String parentBrowser= it.next();
String childBrowser = it.next();
driver.switchTo().window(childBrowser);
Thread.sleep(3000);

driver.close(); //close the current window(Child Browser)
driver.switchTo().window(parentBrowser); //Switch to Parent Browser



----------------------------------------------------------------------------------------------------------------------------- -


11. CALENDAR POPUPS
Calendar PopUp - 1

Normal Calender(current month) Popup can be handled in the following way.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Calender element and click to open.
4. Fetch the required date through xpath and click.


/*IRCTC calendar*/
driver.findElement(By.id("calendar_icon1")).click();
driver.findElement(By.xpath("//div[@id='CalendarControl']/table[tbody[tr[td[text()='Octobe
r 2012']]]]/descendant::a[text()='5']")).click();
------------------------------------------------------------------------------------------------------------------------------

Calendar PopUp - 2 (Customized wait)

In a Calender if we want to click on future month which is not currently displayed, we need
to click on next link until we get the required month.
This can be done by writing Customized wait. Check for particular date element in
each month, if not found move to next month.

/*makemytrip calendar*/
driver.get("http://www.makemytrip.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("deptDateRtripimgExact")).click(); //find Calendar
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
boolean flag=true;
while(flag){
try {
WebElement el = driver.findElement(By.xpath("//div[contains(@class,'ui-datepicker-group')
and descendant::span[text()='March']]/descendant::a[text()='5']")); // Required future
date
if(el !=null) //Check if the required date element is found or not
{
el.click(); // if required Date is found, then click the date
flag=false;
}
}
catch (Exception e) { //Catches exception if no element found
try {
Thread.sleep(500);
driver.findElement(By.xpath("//a[@title='Next']")).click(); //Click on next month
}
catch (InterruptedException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
----------------------------------------------------------------------------------------------------------------------------- -

12. DROP DOWN MENU


In order to click on an menu item, first we need to move the mouse over Parent menu,
later we can click on any of the Menu child item.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the MENU Parent element and create a WebElement object.
4. Create an Action object for Driver
5. Through Action object, move to Parent element.
6. Give a Delay for menu items to be displayed.
7. Fetch the Child item through xpath and Click on it.

WebElement parentMenu = driver.findElement(By.linkText("Tourist Trains"));
Actions act = new Actions(driver); // Create an Action object
//move to the parent menu item
act.moveToElement(parentMenu).build().perform();
Thread.sleep(3000); //wait till the child items are displayed
driver.findElement(By.linkText("Bharat Tirth")).click();

----------------------------------------------------------------------------------------------------------------------------- -


13. CONTEXT CLICK (RIGHT CLICK)
We can use keyboard keys to Make a Right Click.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Fetch the MENU Parent element and create a WebElement object.
4. Create an Action Object for Driver.
5. Through Action Object, make a Context Click on Menu Parent object.
6. Through Action Object, send keys for ARROW_DOWN/ARROW_UP/Keys.ENTER.


Example

WebElement parentMenu = driver.findElement(By.linkText("Tourist Trains"));

Actions act = new Actions(driver); //Create Action object for Driver

act.contextClick(parentMenu).build().perform(); //Context Click

act.sendKeys(Keys.ARROW_RIGHT).build().perform();
Thread.sleep(1000);
act.sendKeys(Keys.ARROW_DOWN).build().perform();
Thread.sleep(1000);
act.sendKeys(Keys.ENTER).build().perform();

----------------------------------------------------------------------------------------------------------------------------- -

14. JAVA SCRIPT EXAMPLE
We can use java script command to perform actions.
We can write code to fill up the text box through java script.

Please follow the steps mentioned below.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Create Java Script executor object for the Driver.
4. Store the Java Script command in a String Variable.
5. Java Script Executor object executes the command in the Variable.


JavascriptExecutor js = (JavascriptExecutor) driver;
String jsCmd = "document.getElementsByName('city')[0].value='ban'";
js.executeScript(jsCmd);
------------------------------------------------------------------------------------------------------------------------------

15. MULTIPLE ELEMENTS
We can count the number of links present in the page. We can also print the link text of
each Web link.


Please follow the steps mentioned below.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Fetch elements with tag //a in the entire page, store it in a List.
4. Get the count of Links present in the Page.
5. Loop through the links and print the Attributes


List allLinks= driver.findElements(By.xpath("//a"));
//display the count of links in the page
System.out.println(allLinks.size());
//display the text for each link on the page
for(int i=0;i
{
//display href for each link
System.out.println(allLinks.get(i).getAttribute("href"));
//display text for each link
System.out.println(allLinks.get(i).getText());
//perform click action
allLinks.get(i).click();

}

------------------------------------------------------------------------------------------------------------------------------

16. Other Browser (Internet Explorer)


Using Internet Explorer with Web Driver.
Please follow the steps mentioned below.
1. Set System Property for the Driver and give path of the IE Driver.
2. Create an Web Driver Object.
3. Open an URL

System.setProperty("webdriver.ie.driver", "D:\\sel\\browserdrivers\\IEDriverServer.exe");


WebDriver driver =new InternetExplorerDriver();
driver.get("www.google.com");
------------------------------------------------------------------------------------------------------------------------------

17. OTHER BROWSER (CHROME)
Using Chrome with Web Driver.
Please follow the steps mentioned below.

1. Set System Property for the Driver and give path of the Chrome Driver.
2. Create an Web Driver Object.
3. Open an URL



System.setProperty("webdriver.chrome.driver",
"D:\\sel\\browserdrivers\\Chromedriver.exe");

WebDriver driver = new ChromeDriver();
driver.get("www.google.com");
----------------------------------------------------------------------------------------------------------------------------- -

18. PROXY SETTINGS.
Please follow the steps mentioned below.

1. Import Selenium.Proxy
2. Create a Profile object for Firefox
3. Create a string variable with value.
4. Create a Proxy object.
5. Set the values through proxy.
6. Set the proxy preference to proxy object using profile object.
7. Pass the profile object to Firefox Driver.



import org.openqa.Selenium.Proxy

FirefoxProfile profile = new FirefoxProfile();
String PROXY = "xx.xx.xx.xx:xx";
Proxy proxy = new Proxy();
proxy.HttpProxy=PROXY;
proxy.FtpProxy=PROXY;
proxy.SslProxy=PROXY;
profile.SetProxyPreferences(proxy);
FirefoxDriver driver = new FirefoxDriver(profile);



----------------------------------------------------------------------------------------------------------------------------- -
19. PAGE ONLOAD AUTHENTICATION
Sometimes when you are Automating Web pages, you may come across Page onload
Authentication window. This window is not java popup/div. It is windows popup. Selenium
directly cannot handle this windows popup.
Hence we use Autoit sowftware tool. Through Selenium we can handle this situation using
Autoit.

Please follow the steps mentioned below.
1.Download Autoit from the following URl
( http://www.autoitscript.com/site/autoit/downloads/ )
2.Install downloaded software.
3. Open Script Editor
Start=>ProgramFiles=>AutoIt =>SciTE Script Editor.
4.Open Object Identifier.
Start=>ProgramFiles=>AutoIt =>AutoIt Window Info.
5.Drag and Drop finder tool in AutoIt Window Info, to the Window you need to identify.
6.Collect the Title Name of window from (AutoIt Window Info.)
7.Write the Script in the Editor.
----------------------------------------------------AUTOIT CODE-----------------------------------------------------

WinWaitActive("Authentication Required")
Send("admin")
Send("{TAB} admin{TAB} {ENTER}")
------------------------------------------------------------------------------------------------------------------------------
8.Save the file as default save.(Authentication1.exe)
9.RUN/Compile the SCRIPT, it creates an exe.
10.Mention the exe path in the Program before creation of Driver.

EXAMPLE:


Process P = Runtime.getRuntime().exec("D:\\java_prj\\SELENIUM
WEBDRIVER\\AUTOIT\\Authentication1.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://192.168.1.1");
------------------------------------------------------------------------------------------------------------------------------
20. FILE DOWNLOAD
Please follow the steps mentioned below.

1. Create a PROFILE object of Browser.
2. Set Preference, by giving Download destination Directory.
3. Set Preference, by giving Default Folder. 0 => Desktop, 1=>System Default Location, 2
=> Indicates a custom Folder Location
4. Set Preference, A comma-separated list of MIME types to save to disk without asking
what to use to open the file. Default value is an empty string.

After coding the above mentioned steps, now start the driver and click on Download
button/link.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Fetch the Download web element and click.


FirefoxProfile Prof = new FirefoxProfile();
Prof.setPreference("browser.download.dir", "D:\\java prj");
Prof.setPreference("browser.download.folderList", 2);
Prof.setPreference("browser.helperApps.neverAsk.saveToDisk","application/zip");

WebDriver driver = new FirefoxDriver(Prof);
driver.get("http://seleniumhq.org/download/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);
driver.findElement(By.xpath("//a[@name='client-
drivers']/table/tbody/tr[1]/td[4]/a")).click();

----------------------------------------------------------------------------------------------------------------------------- -
21. FILE UPLOAD
Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Store the Source path of file in a variable.
4. Fetch the Upload web element text box and give path using variable.
5. Fetch the upload button and click


WebDriver driver = new FirefoxDriver();
driver.get("http://www.2shared.com/");
String FilePath = "C:\\Users\\abc\\Desktop\\test.xml";
driver.findElement(By.id("upField")).sendKeys(FilePath);
driver.findElement(By.xpath("//input[@type='image']")).click();
------------------------------------------------------------------------------------------------------------------------------

22. HANDLING JAVA ALERT
Sometimes you may get alerts as anticipated(through Insert/update/delete operation in
database). These may be JAVA alerts.
Please follow the steps mentioned below to handle Alerts.

1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. You get an alert asking to click on 'YES' or 'NO' button.
4. First Confirm if it is JAVA alert window.
5. Write a code to switch the control to Alert window.
6. In the Alert window, either ACCEPT by clicking on 'YES'
or CANCEL by clicking on 'NO'.


WebDriver driver = new FirefoxDriver();
driver.get("http://www.2shared.com/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);

Alert alert = driver.switchTo().alert();
alert.accept();
//or
alert.dismiss();

----------------------------------------------------------------------------------------
How to handle flex in selenium web driver?
Hello dear there are some steps you need to follow.
1. you have to download selenium flex api .
2. you will get a SeleniumFlexAPI.swc file here.
a. you need to put this file in your flex application.
b. you need to add lib path in flex compiler like this and comile the code
-include-libraries "libs\SeleniumFlexAPI.swc"
answered Feb 28 by seleniumGuru (2,580 points)
selected Feb 28 by tester
flag

ask related question

comment

3.you can make a java file with this code.
package com.kdf;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FlexWebDriver {
private final WebDriver webDriver;
private final String flashObjectId;
public FlexWebDriver(final WebDriver webDriver, final String flashObjectId) {
this.webDriver = webDriver;
this.flashObjectId = flashObjectId;
}


public String doFlexClickMenuBarUIComponent(final String objectId, final String optionalButtonLabel) {
return call("doFlexClickMenuBarUIComponent", objectId, optionalButtonLabel);
}

public String doFlexClickMenuBarUIComponent(final String objectId) {
return doFlexClickMenuBarUIComponent(objectId, "");
}
public String click(final String objectId, final String optionalButtonLabel) {
return call("doFlexClick", objectId, optionalButtonLabel);
}

public String click(final String objectId) {
return click(objectId, "");
}
public String ClickDataGridItem(final String objectId, final String optionalButtonLabel) {
return call("doFlexClickDataGridItem", objectId, optionalButtonLabel);
}

public String ClickDataGridItem(final String objectId) {
return click(objectId, "");
}

public String FlexClickDataGridUIComponent(final String objectId, final String optionalButtonLabel) {
return call("doFlexClickDataGridUIComponent", objectId, optionalButtonLabel);
}

public String FlexClickDataGridUIComponent(final String objectId) {
return FlexClickDataGridUIComponent(objectId, "");
}

public String FlexSelectComboByLabel(final String objectId, final String optionalButtonLabel) {
return call("doFlexSelectComboByLabel", objectId, optionalButtonLabel);
}

public String doFlexSelectComboByLabel(final String objectId) {
return click(objectId, "");
}
public String FlexSelect(final String objectId, final String optionalButtonLabel) {
return call("doFlexSelect", objectId, optionalButtonLabel);
}

public String FlexSelect(final String objectId) {
return FlexSelect(objectId, "");
}
public String FlexRefreshIDToolTips(final String objectId, final String optionalButtonLabel) {
return call("doFlexRefreshIDToolTips", objectId, optionalButtonLabel);
}

public String FlexRefreshIDToolTips(final String objectId) {
return FlexRefreshIDToolTips(objectId, "");
}
public String FlexDoubleClick(final String objectId, final String optionalButtonLabel) {
return call("doFlexDoubleClick", objectId, optionalButtonLabel);
}

public String FlexDoubleClick(final String objectId) {
return FlexDoubleClick(objectId, "");
}
public String FlexSetFocus(final String objectId, final String optionalButtonLabel) {
return call("doFlexSetFocus", objectId, optionalButtonLabel);
}

public String FlexSetFocus(final String objectId) {
return FlexSetFocus(objectId, "");
}
public String FlexMouseMove(final String objectId, final String optionalButtonLabel) {
return call("doFlexMouseMove", objectId, optionalButtonLabel);
}

public String FlexMouseMove(final String objectId) {
return FlexMouseMove(objectId, "");
}
public String FlexType(final String objectId, final String optionalButtonLabel) {
return call("doFlexType", objectId, optionalButtonLabel);
}

public String FlexType(final String objectId) {
return FlexType(objectId, "");
}

public String getFlexDataFieldLabelForGridRow(
String dataGridId, String field, int row) {
return call("getFlexDataGridFieldLabelForGridRow", dataGridId, field, Integer.toString(row));
}
public int getFlexDataGridRowCount(String dataGridId ) {
return Integer.parseInt(call("getFlexDataGridRowCount", dataGridId));
}
public int getSelectionIndex(String selectionFieldId) {
return Integer.parseInt(call("getFlexSelectionIndex", selectionFieldId, ""));
}

//... Omitted for clarity ...

private String call(final String functionName, final String... args) {final Object result =
((JavascriptExecutor)webDriver).executeScript(
makeJsFunction(functionName, args),
new Object[0]);

return result != null ? result.toString() : null;
}

private String makeJsFunction(final String functionName, final String... args) {
final StringBuffer functionArgs = new StringBuffer();

if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (i > 0) {
functionArgs.append(",");
}
functionArgs.append(String.format("'%1$s'", args[i]));
}
}
return String.format(
"return document.%1$s.%2$s(%3$s);",
flashObjectId,
functionName,
functionArgs);
}


}

Now you can use these functions in your selenium file.

----------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------

Potrebbero piacerti anche