There are two main ways to create Java Strings. One is by creating a String literal (see top line in picture below). The other is to explicitly create a new Object in memory (See second line below). I will avoid going into detail about how these differ as it involves discussing aliasing and how Java saves memory. Note: Unlike some other programming languages, in Java Strings must be enclosed in double quotes. Single quotes are used for chars, a primitive data type. 
 
Important Methods of a Java String 
 String Concatenation 
 To concatenate Strings (join to Strings), the easiest way to do it is just use the + operator as shown in the example below 

tring abcAsVariable ="abc"; 
String defAsVariable ="def"; 
String abcdef = "abc" + "def"; 
You could achieve the same concatenation by using the variables as shown in the next line.
String abcdef = defAsVariable + abcAsVariable ; 

How to Declare and Initialize a String in Java


import java.awt.Label;
import java.io.File;
import java.io.IOException;

import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.Number;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class Jmeter {
 public static void main(String asp[]) throws BiffException, IOException
 {
   
  Workbook workbook = Workbook.getWorkbook(new File("C:\\Frame11.xls"));
  WritableWorkbook wbook1 = Workbook.createWorkbook(new File("C:\\Nitin.xls"));
  Sheet sheet = workbook.getSheet(0);
  Cell cell =sheet.getCell(0, 0);
  Cell cell1 =sheet.getCell(0, 1);
  Cell cell2 =sheet.getCell(0, 2);
  String s = cell.getContents();
  String s1 = cell1.getContents();
  String s2 = cell2.getContents();
  System.out.print("HEllo   "+s+"  "+s1+"     "+s2);
        WritableSheet ws = wbook1.createSheet("FIRSTSHEET", 0);
        Number num = new Number(0, 1, 25.5285);
        wbook1.write();
        wbook1.close();

 }

WRITING DATA TO EXCEL(Code)


import java.io.File;
import java.io.IOException;

import jxl.*;
import jxl.read.biff.BiffException;
public class Jmeter {
 public static void main(String asp[]) throws BiffException, IOException
 {
   
  Workbook workbook = Workbook.getWorkbook(new File("C:\\Frame11.xls"));
  Sheet sheet = workbook.getSheet(0);
  Cell cell =sheet.getCell(0, 0);
  Cell cell1 =sheet.getCell(0, 1);
  Cell cell2 =sheet.getCell(0, 2);
  String s = cell.getContents();
  String s1 = cell1.getContents();
  String s2 = cell2.getContents();
  System.out.print("HEllo   "+s+"  "+s1+"     "+s2);
  
 }

 
};

READING DATA FROM EXCEL(Code)


Step 1: For that first we need to import SeleniumServer class
Which exist in following package.

Import org.openqa.selenium.server.*;


Step 2: Now we need to create SeleniumServer object.

SeleniumServer sr = new SeleniumServer(rc);

Here I am creating selenium server object and passing configuration object as an argument.


Step 3: We need to boot selenium server.


sc.boot(); 

Step 4: Stating Selenium Server

sc.start();


STARTING SELENIUM SERVER using Java code


While working with selenium server first we need to setup configuration of selenium server, like on which port the server will run, Avoid proxy setting, start logs etc.

For working with Selenium server configuration, we need to perform following tasks.

1 Add selenium server jar file in build path of current project.

2 Import org.openqa.selenium.sever.RemoteControlConfiguration;

Here we have imported selenium sever Rcmote Control Configuration Class, we can need to create object of that class and then we can use methods of the class to ser remote control server configuration.


3 Create RemoteControlConfiguration object

RemoteControlConfiguration rc = new RemoteControlConfiguration();


4 Set Port 

 rc.setPort(4444);

5 Set Proxy

 rc.setAvoidProxy(true)

6 Set Browser side logs

rc.setBrowserSideLogsEnabled(true)

By this way we can set as much settings as we want in RemoteControlConfiguration


Selenium Server settings


                 For setting Remote Control Server configuration,

1 Create a Remote Control Configuration object.

2 We have multiple methods for that

3 We can use method like setPort to ser port etc, like this we have many properties that can be use for server settings.

4 We can pass these configuration object to server pobject.



                  For Enable/ Disable Java script etc

1 We can use user-extensions.js file and these we can set different browser settings.


                  For rest of the work, we can use Twist.properties file

The Selenium configurations are defined in the twist.properties file. This file can be accessed by searching for it using Ctrl+Shift+R while at the workbench or by switching to the Java perspective.

Working With Server Configuration


Java script is used for client side scripting

Java script is mainly used for validation, it make page more interactive, can respond to an action.

Can create/ delete cookies, can do other browser work.

Java Script is case sensitive.

Javascript (for Selenium IDE)


 -port <nnnn>: the port number the selenium server should use
    (default 4444)
  -timeout <nnnn>: an integer number of seconds before we should give
    up
  -interactive: puts you into interactive mode.  See the tutorial for
    more details
  -singleWindow: puts you into a mode where the test web site
    executes in a frame. This mode should only be selected if the
    application under test does not use frames.
  -profilesLocation: Specifies the directory that holds the profiles
    that java clients can use to start up selenium.  Currently
    supported for Firefox only.
  -forcedBrowserMode <browser>: sets the browser mode to a single
    argument (e.g. "*iexplore") for all sessions, no matter what is
    passed to getNewBrowserSession
  -forcedBrowserModeRestOfLine <browser>: sets the browser mode to
    all the remaining tokens on the line (e.g. "*custom
    /some/random/place/iexplore.exe") for all sessions, no matter what
    is passed to getNewBrowserSession
  -userExtensions <file>: indicates a JavaScript file that will be
    loaded into selenium
  -browserSessionReuse: stops re-initialization and spawning of the
    browser between tests
  -avoidProxy: By default, we proxy every browser request; set this
    flag to make the browser use our proxy only for URLs containing
    '/selenium-server'
  -firefoxProfileTemplate <dir>: normally, we generate a fresh empty
    Firefox profile every time we launch.  You can specify a directory
    to make us copy your profile directory instead.
  -debug: puts you into debug mode, with more trace information and
    diagnostics on the console
  -browserSideLog: enables logging on the browser side; logging
    messages will be transmitted to the server.  This can affect
    performance.
  -ensureCleanSession: If the browser does not have user profiles,
    make sure every new session has no artifacts from previous
    sessions.  For example, enabling this option will cause all user
    cookies to be archived before launching IE, and restored after IE
    is closed.
  -trustAllSSLCertificates: Forces the Selenium proxy to trust all
    SSL certificates.  This doesn't work in browsers that don't use the
    Selenium proxy.
  -log <logFileName>: writes lots of debug information out to a log
    file
  -htmlSuite <browser> <startURL> <suiteFile> <resultFile>: Run a
    single HTML Selenese (Selenium Core) suite and then exit
    immediately, using the specified browser (e.g. "*firefox") on the
    specified URL (e.g. "http://www.google.com").  You need to specify
    the absolute path to the HTML test suite as well as the path to the
    HTML results file we'll generate.
 

Selenium Server Interactive


 It is same as object repository of QTP.
 Rather than giving element locator in target, we place it in Map file and use logical name.

ADVANTAGE

 With this, it is easy to understand script, make script more readable.
  It is easy to maintain script, it any locator change, we need to change it only in map file and it  will reflect at all places.
 It is a java script file so in case of any error it will throw exception(easy debug)

Once we create and attach map file, any recording will display logical name in IDE
After any change in file, we need to restart IDE to reflect changes

UI MAPPING IN SELENIUM IDE


1 toUpperCase()   ::  Convert string to upper case

2 toLowerCase()   ::  Convert string to lower case

3 valueOf              :: Convert given value to string.

4 equals                :: Check  2 strings are equal or not.

5 equalsWithIgnoreCase ::  Check  2 strings are equal or not(case insensitive).

6 subString  ::    return substring to given string.

7 Replace    :: replace a value in given styring.

8 trim()       :: is used to removing blanks from start and end of string.

9 Split()      :: split string on basis of given regular exp.

10 Length     :: return length of the string

11 Concat :: Concatenate the two string. 
 
12 IndexOf :  to find the index of first occurrence of character.

13 LastIndexOf : to find the index of first occurrence of character.


Important String Functions in JAVA


Step 1:  Create a Class Object where that Method Exists

Framework ex = new Framework();


Step 2: now create a object of Type METHOD

Method meth;


Step 3: Now we need to call, 

getClass() method of class object, which will return class object
then  call getDeclatedMethod(“MethodNAme”,TypeofArgument);:- it will return method object which is passed in first argument.

meth = ex.getClass().getDeclatedMethod(“readWorkBook1”,String.class); 

String.class
Int.Class
Null  : -  if no argument



Step 4: Use invokemethod of Method object to call that method.

meth.invoke(classobject,null)

Here in this, we need to pass classobject as a first argujment and data to the second argument.

meth.invoke(ex,null);


WORKING WITH REFLECTION API


To work with DB, first we need to make connection with DB and then need to execute our SQL/PL-SQL commands, for connection we have few steps.

Step 1:  import java.sql.* package

import java.sql.*;

Step 2: Load Drivers

We use class.forName keyword to load drivers, it takes string of driver class as an argument, return a class 
 
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

Class name which is passed here as an argument is for JDBC ODBC driver, we can use any other driver if required.


Step 3  : Create a DSN(Data source name object, if we don’t create DSN, we can pass DSN string directly to connection string.

Step 2: We should have DSN for Excel, we can do it by 2 ways 

Way-1

Go to Control Panel
          Administrative Tools 
          Data Source 
          System DSN
          ADD
          Select XLS Driver
           
          FINISH
         GIVE DSN NAME
         SELECT WORKBOOK WHICH WE WANT TO WORK
 

Work Done…………..

Way-2   Do it by coding

String Db;
Db =   “JdbcOdbcDriver={Microsoft Excel Driver (*.xls)};DBQ=C:\abc.xls”;DriverID=22;ReadOnly=False”



Step 3:  Create Connection Object 

If we used way 1 then connection object will be created like 

Connection con = DricverManager.getConnection(“jdbc.odbc.DSNNAME”)

DSNNAME =  what we have set when we created DSN from admin tools

OR 

If we used way 2 then connection object will be created like that

Connection Con = DriverManager.getConnection(DSNString,””,””)

DSNString = created in step 2


Step 4: Statement Object 

Statement s = Con.createstatement();

Step 5: Resultset Object or ResultSetMetaData object
Resultset r  = s.ExecuteQuery(“Select * from [Sheet1$]”) ;

ResultsetMetaData rm =r.getmetadara();


Result set object is used to hold data returned by query
Resultsetmetadata object Is used to hold information about data

ResultSetMetaData rm = rs.getMetaData();
        x =rm.getColumnCount();


WORKING WITH EXCEL THROUGH JDBC


Step 1 Download : - https://github.com/dwdyer/reportng/downloads

Step 2: Add these 2 jar files(velocity-dep.jar, reporting.jar) to project build path

Step 3: Add listeners in testng.xml

<listeners>
      <listener class-name="org.uncommons.reportng.JUnitXMLReporter"></listener>
      <listener class-name="org.uncommons.reportng.HTMLReporter"></listener>
</listeners>

Step 4: Download Guise.jar

http://www.findjar.com/jar/com.google.code.guice/jars/guice-1.0.jar.html

  Add it to project build path.

 
Step 5:   Go to Project Properties- TestNg- Disable default listener

Report generated by ReportNg


When we run any test, TestNG automatically generates report which are saved in project folder, report contain many text file and html file, but we need to go for 

            Index.html

We have “testng.css” file in same folder which can be modified to change colour schemes etc.

It also generate XML file which can be used by Junit to generate report.

We can also enter our Data to TestNg reports

 Import org.testng.Reporter; (import this class)
 Reporter.log (“Data”)    // use log method to enter data


Reports generated by Test NG


Reporting in selenium can be done in many ways, few common ways are

1 Html reports by Junit

2 Html reports by TestNg

3 Html reports by ReportNG

4 XSLT Reports

REPORTING IN SELENIUM


C:\Program Files\Java\jdk1.6.0\bin\selenium>java -jar selenium-server-standalone
.jar -singleWindow -port 4445 -htmlSuite "*firefox" "http://mail.in.com" "C:\Doc
uments and Settings\admin\My Documents\Selenium\ABSP.html" "C:\Documents and Set
tings\admin\My Documents\Selenium\HH.html"

Run selenium IDE cases on multiple browser


// Paramter annotation in junit
@RunWith(value=Parameterized.class)
public class Case2 {
 String uname, pass;
 public Case2(String uname, String pass)
 {
  this.uname = uname;
  this.pass = pass;
 }
 
 @Test
 public void TestCase()
 {
   System.setProperty("webdriver.chrome.driver","C:\\Documents and Settings\\Administrator\\My Documents\\Downloads\\chromedriver_win32_2.1\\chromedriver.exe");
   ChromeDriver f = new ChromeDriver();
   f.get("http://mail.in.com");
   f.findElementById("f_id").sendKeys(uname);
   f.findElementById("f_pwd").sendKeys(pass);
   f.findElementByClassName("signin");
 }
 
 @Parameters
 public static List Para()
     {
  Object arr[][]={{"uname","pass"},
            {"uname1","pass1"},
            {"unam22","pass2"}};
  return Arrays.asList(arr); 
  }
 }



Parameter annotation in Junit code


                                  Parameter Annotation In Junit
Parameter annotation work same as we do in DataProvider annotation
Here we use 2 annotations
   1 Parameter annotation
   2 Run With Annotation

@Parameter annotation
Method under the parameter annotation is a static method
This return a list
Value returned by Parameter annotation need to be assigned to variable in constructor


@RunWith annotation
@RunWith(Parameterized.Class)
Need to pass it before class to show that class will run with parameters

Parameter annotation in Junit


 System.setProperty("webdriver.chrome.driver","C:\\Documents and Settings\\Administrator\\My Documents\\Downloads\\chromedriver_win32_2.1\\chromedriver.exe");
   ChromeDriver f = new ChromeDriver();
   f.get("http://mail.in.com");
   f.findElementById("f_id").sendKeys("uname");
   f.findElementById("f_pwd").sendKeys("pass");
   f.findElementByClassName("signin");
   XmlSuite suite = new XmlSuite();
   suite.setName("OMS");
   XmlTest test1 = new XmlTest(suite);
   test1.setName("TCase1");
   List<XmlClass> classes = new ArrayList<XmlClass>();
   classes.add(new XmlClass("org.nitin.TCase1"));
   List<XmlSuite> suite_a = new ArrayList<XmlSuite>();
   suite_a.add(suite);
   TestNG tng = new TestNG();
   tng.setXmlSuites(suite_a);
   tng.run();
 

Generate TestNg.xml Dynamically code


With the help of element locators we try to locate an element on AUT uniquely.

 
The different types of locator are:
 ID
   
 Name

 Identifier( Works only in RC, check value with ID if not found then match with name)

   Identifier= name or id (if we don’t pass identifier=, it default assume, this is an identifier

 Link Text

 CSS Selector
•   Tag and ID
•   Tag and class
•   Tag and attribute
•   Tag, class, and attribute
•   Inner text

 DOM (Document Object Model)
•   getElementById
•   getElementsByName
•   dom:name
•   dom:index

 XPath

COMMON ELEMENT LOCATORS IN SELENIUM


Create Object Repository in Selenium
Step -1    Create a file object and make a connection with xls file from which we want to pick data
        File f = new File(“C:\\abc.xls”)                 Here we have given an absolute path to the file
        File  f= new File(“./src/input.xls”);

Step-2  Create a file object and make a connection with properties file to which we want to place data
        File f = new File(“C:\\abc.properties”)                 Here we have given an absolute path to the file
        File  f= new File(“./src/test.properties”);

Step-3   Create an object for Properties class
               Properties p = new Properties();

Step-4   Add properties to properties file

      p.setproperty(“propname”,”Propvalue”);
* Add all properties that we want to add

Step-5   Create  a FileOutputStream object
FileOutput stream is used to write data to any output file.
 FileOutputStream f1= new FileOutputStram(fileobjectforpropertyfile)
Prop.store(f1,”Message For First Line”)
f1.Close();

Creating Properties File Dynamically


public class Test1 {
 
@Test
public void TestC() throws IOException
    {
 FirefoxDriver f = new FirefoxDriver();
 f.get("http://www.rediffmail.com/");
 Set<String> winh=   f.getWindowHandles();
 Iterator iter= winh.iterator();
 File fnew= f.getScreenshotAs(OutputType.FILE);
 FileUtils.copyFile(fnew, new File("C:\\abc111.png"));
    }
}


Program to take screenshot in webdriver


It will take screenshot of entire page as we do in captureentirepagescreensshot
WebDriver has provided us one  interface TakesScreenshot  for capturing the screenshot of web application and This interface provides one method names as getScreenshotAs() to capture screenshot in instance of driver.

           This getScreenshotAs() method takes argument of type 
           OutputType.File 
           or OutputType.BASE64
           or Output.BYTES. 


File scrnshot= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
OR  ((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);
OR  ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
NOTE: Here in brackets((TakesScreenshot) is not mandatory it is just showing this driver implemented this getScreenshotAs method from “TakesScreenshot” interface

We have taken the screenshot with the help of getScreenshotsAs() method and  and now its time to copy this file somewhere in our file system or in our desktop.

 For this purpose we further use copyFile() method of the FileUtils class from theorg.apache.commons.io.FileUtils class.
Placing file in file system by using this line
FileUtils.copyFile(scrFile, new File(“e:\\main_page.png”));

Taking Snapshots in WebDriver


captureEntirePageScreenshot
1. This captures the AUT web page only
2. This supports only mozilla firefox( available for firefox (*chrome mode) )
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.


Difference between CaptureScreenShot & captureEntirePageScreenshot


We have 2 different methods
a)   Capturescreenshot
b)   Captureentirepagescreenshot

CaptureScreenshot  Take snapshot of screen and save it to given location.
Selenium.capturescreenshot(“C:\\abc.png”);

private Selenium selenium;
 @Before
 public void broStart()
 {
  selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://mail.in.com");
  selenium.start();
 }
 
 @Test
 public void case1() throws InterruptedException
 {
  Thread.sleep(2000);
  selenium.captureScreenshot("C:\\Abc.png");
  
 }



CaptureEntirePageScreenshot(Arg1,Arg2)
Arg1=> Location where we want to save screenshot
Arg2=> Background Color

Take snapshot in Selenium RC

File f= new File("G:\\Frame1111_1.xls");
WritableWorkbook wk= Workbook.createWorkbook(f);
WritableSheet ws = wk.createSheet("Data", 0);
Label l1= new Label(2, 3, "HELLO");
ws.addCell(l1);
wk.write();
wk.close();

Write Data to Excel using JXL API(Code)


WebDriverBackedSelenium is a kind of class name where we can create an object for it as below:


Selenium wbdriver= new WebDriverBackedSelenium(WebDriver object name, "URL path of website")
The main use of this is when we want to write code using both WebDriver and Selenium RC , we must use above created object to use selenium commands.

What is WebDriverBackedSelenium 


Python, Ruby, C# and Java are all supported directly by the development team. There are also webdriver implementations for PHP and Perl.

What are the languages supported by WebDriver


We can use implicit wait.

Syntax- driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

Here it will wait for 10sec if while execution driver did not find the element in the page immediately. This code will attach with each and every line of the script automatically. It is not required to write every time. Just write it once after opening the browser.


How do you achieve synchronization in WebDriver


Both methods are abstract method of WebDriver interface and used to find the WebElement in a web page.

findElement() – it used to find the one web element. It return only one WebElement type.

findElements()- it used to find more than one web element. It return List of WebElements.


What is the difference between findElement and findElements


a) Manual testing of all work flows, all fields, all negative scenarios is time and cost consuming.

b) It is difficult to test for multi lingual sites manually.

c) Automation does not require human intervention. We can run automated test unattended(Overnight).

d) Automation increases speed of test execution.

e) Automation helps increase test coverage.

f) Manual testing can become boring and hence error prone.


Why do we go for automation testing


a) Encapsulation,

b) Abstraction,

c) Polymorphism,

d) Inheritance.

What are oops concepts


a) It does not supports looping or conditional statements. Tester has to use native languages to write logic in the test case.

b) It does not supports test reporting, you have to use selenium RC with some external reporting plugin like TestNG or JUint to get test execution report.

c) Error handling is also not supported depending on the native language for this.

d) Only support in Mozilla FireFox only. Its an Firefox add on.


What are the limitations of Selenium IDE


getWindowHandles()- is used to get the address of all the open browser and its return type is Iterator<String>.

getWindowHandle()- is used to get the address of the current browser where the conrol is and return type is String.

What is the difference b/w getWindowHandles() and getWindowHandle()


 Some times while doing testing with selenium, we get stuck by some interruptions like a window based pop up. But selenium fails to handle this as it has support for only web based application. To overcome this problem we need to use AutoIT along with selenium script. AutoIT is a third party tool to handle window based applications. The scripting language used is in VBScript

What is the use of AutoIt tool ?


a) What is the frame work.

b) Which frame work you are using.

c) Why This Frame work.

d) Architecture.

e) Explanation of every component of frame work.

f) Process followed in frame work.

g) How & when u execute the frame work.

h) Code (u must write code and explain).

i) Result and reporting .


While explaining the framework, what are points which should be covered ?

a) TestNG allows us to execute of test cases based on group.

b) In TestNG Annotations are easy to understand.

c) Parallel execution of Selenium test cases is possible in TestNG.

d) Three kinds of report generated

e) Order of execution can be changed

f) Failed test cases can be executed

g) Without having main function we can execute the test method.

h) An xml file can be generated to execute the entire test suite. In that xml file we can   rearrange our execution order and we can also skip the execution of particular test case.


What are the benefits of using TestNG ?


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

How to maximize window using selenium 2.0?


WebElement source  =  driver.findElement(By.id("Source ElementID"));
WebElement destination  =  driver.findElement(By.id("Taget ElementID"));

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

How to perform drag and drop in selenium 2.0?


WebElement el  =  driver.findElement(By.id("ElementID"));

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

How to double click on element using selenium 2.0?


String title =  driver.getTitle()

How to capture page title using Selenium 2.0?


WebElement el = driver.findElement(By.id("Radio button id"));

//to perform check operation
el.click()

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

How to automate radio button in Selenium 2.0?


JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("pass your java scripts");

How to execute java scripts function.


WebDriver would support handling js alerts using Alert interface.
                 // Bring control on already opened alert
          Alert alert = driver.switchTo().alert();
          // Get the text of the alert or prompt
          alert.getText();
// Click ok on alert
          alert.accept();

How do I handle java script alert using WebDriver?


public void highlightElement(WebDriver driver, WebElement element) {
    for (int i = 0; i < 2; i++) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                element, "color: yellow; border: 2px solid yellow;");
        js.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                element, "");
    }
}

Highlight elements with Selenium WebDriver


1. Download ANT http://ant.apache.org/

2. Unzip it and rename it to ant

3.Set environmental variables JAVA_HOME to your Java environment, ANT_HOME to the directory you uncompressed, to do it on command prompt type this (Assume Ant is installed in E:\ant\.)

set ANT_HOME=E:\ant
set JAVA_HOME=D:\Program Files\Java\jdk1.6.0_03
set PATH=%PATH%;%ANT_HOME%\bin
In windows 7 you can go to Control Panel\All Control Panel Items\System or right click on Computer and then to “Advance system setting”

-Choose Advanced Tab
-Press  Environtmen Variables Button
-In the System Variables, click New Button
Give the Variable Name:ANT_HOME
Give the Value: E:\ant
Click OK

Then,we’ll add new ANT_HOME path,
And Click again on New Button if you do not have ‘path’ Variable in there, if so select it and edit as Give the Variable Name:pathGive the Value D:\Program Files\Java\jdk1.6.0_03\bin;%ANT_HOME%\binClick OK

4. Check wheter ANT works correctly or not.
In the command prompt, type:ant -version

Installing ANT for Windows 7


final Runtime rt = Runtime.getRuntime();
try {
Process p = rt.exec(“cmd /C C:\folder\project\mybat.bat”); 
} catch (final IOException e) {
throw new RuntimeException(“Failed to run bat file.”);
}

Code to run batch file in Webdriver


public static int getRowCount(WebElement element) throws Exception {
try {
WebElement table =element;
List rows = table.findElements(By.tagName(“tr”));
return rows.size();
} catch (Exception e) {
return -1;
}

Get total number of rows from a HtmlTable – Webdriver


Selenium.setSpeed:
1. takes a single argument in string format
ex: selenium.setSpeed(“2000″) – will wait for 2 seconds
2. Runs each command in after setSpeed delay by the number of milliseconds mentioned in setSpeed.

Thread.sleep:
1. takes a single argument in integer format
ex: thread.sleep(2000) – will wait for 2 seconds
2. Waits for only once at the command given at sleep.

What is the difference between Thread.Sleep() and Selenium.setSpeed()?


Assert: Will fail and abort the current test execution.
Verify: Will fail and continue to run the test execution.

What is the difference between an assert and a verify with Selenium commands?


Operating Systems supported by Selenium are:
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+

What are the Operating Systems supported by Selenium

Browsers supported by Selenium RC are:
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

Which are the browsers supported by Selenium RC


 

  // Working with List
  selenium.addSelection("ElementLocator", "Value");
  // Working with Dropdown
  selenium.select("ElementLocator", "Value");

Working with LIST AND DROPDOWN in RC


WEBDRIVER

1st Way         // To Work on dropdown or List we need to create object of Select class
  Select dateselect =  new Select(driver.findElementById("f_mydata"));
  
  // Here we have 3 options to select an element 
  dateselect.selectByIndex(1);
  dateselect.selectByValue("15");
  dateselect.selectByVisibleText("MyData");


2nd Way         // Just Write code in 1 line rather than writing in 2 differnt line

                     new Select(driver.findElementById("f_mydata")).selectByIndex(0);


Working with LIST AND DROPDOWN in Webdriver


This program will return true if element is present else it will return false

public boolean verifyElementPresent(WebDriver driver,String locatorxpath)
 {
  boolean flag=false;
  try
  {
  driver.findElement(By.xpath(locatorxpath));
  flag=true;
  }
  catch(Exception ex)
  {
   flag=false;
  }
  return flag;
 }

Code to Verify an element present or not in Webdriver


How to implement object repository in Selenium
OR
How to manage elements in Selenium
OR
Where do you place element locator in Selenium
 
In selenium, first we pick element locator of all elements on which we are supposed to perform our action and place in a property file(Here property file behave as Object Repository for Selenium)
 
Now wherever in our test case, element locator value is required. We fetch element locator value from properties file(this is called properties file because extension of this file is .properties)
 
To fetch value of element locator from property file, we need to create object of “ResourceBundle” class and by that object we can use getString method


How to implement object repository in Selenium


1 User Friendly, Easy to work on
2 Can develop test cases in much faster way as compared to Selenium
3 Support all type of application(client-server, window , web)
4 Limited programming skills are required
  

Advantage of QTP over Selenium


 
1 Free (No license fees is required)
2 Support large number of browser(QTP support only 3)
3 Support large number of  programming language(C#,  Java, Python, Perl etc), QTP support only VB script
4 With the help of grid we can execute multiple test cases in parallel, ultimately we are saving lot of execution time, this kind of feature not available in QTP

Advantage of Selenium over QTP


// Creating webdriver object
  FirefoxDriver driver = new FirefoxDriver();
  driver.get("http://rediff.com");
  
  // Taking screenshot in Webdriver 
  File outSnapshot = driver.getScreenshotAs(OutputType.FILE);
  
  // Use FileUtils class to copy snapshot taken in previous step to my disk
  FileUtils.copyFile(outSnapshot, new File("C:\\snaps.png"));

Taking snapshot in Webdriver


// Creating webdriver object
  FirefoxDriver driver = new FirefoxDriver();
  driver.get("http://rediff.com");
  
  // getWindowHandles method of driver class return a string
  // this string is a unique key referencing all browsers/open
  // opened by our webdriver, we save all values in a Set
  Set<String> hs = driver.getWindowHandles();
  
  // Iterating to the set and picking all available values
  Iterator<String> iter = hs.iterator();

        // Setting iterator to work until value exist there  
  while(iter.hasNext())
  {
   // Here we can perform different actions on window'
   // here in code we are justr moving to there windows
   // and closing all windows opened by webdriver
     driver.switchTo().window((String) iter.next()).close();
     }

 
 



Multiple Windows handling in Webdriver


 
get() and navigate() both are used to open URL/application in webdriver
 
Difference is that in case of get() method, we can just open a URL while in case of navigate() method, we can use use forward and back button of browser
 
Get() method
driver.get("http://rediff.com");
 
 
Navigate() method
 
driver.navigate().to("http://rediff.com");
driver.navigate().back();
driver.navigate().forward();
 

Difference between get() and navigate() method


Firefox
FirefoxDriver driver = new FirefoxDriver();
 
 
Chrome Driver
 
System.setProperty("webdriver.chrome.driver", "path of chrome driver executable");
ChromeDriver driver = new ChromeDriver();
 
 
IE Driver
 
System.setProperty("webdriver.ie.driver", "path of ie driver executable");
InternetExplorerDriver driver = new InternetExplorerDriver();

Creating Webdriver for different browser


1. Webdriver interact with browser directly(use browser native automation support) so it provide faster execution than RC
 
 
1. Webdriver API is much more object oriented than Selenium RC
2. Provide better AJAX support
3. Provide better Window handling support
4. Support IOS and Android App automation support
5. No need to start selenium server
6. Webdriver API is easily extensible so we can extend action classes and define our own customized actions.
7. Solved Selenium RC “single origin policy”

Advantage of Selenium Webdriver over Selenium RC

 New enhancement in selenium
 Added with Selenium 2.0
 With the help of webdriver we can execute test cases on multiple browser
 Faster execution than Selenium RC
 Better support of multiple window handling
 Better support of Ajax handling
 Support Iphone application
 Support Android application
 No need to start Selenium Server
 Support more element locating options like “PartialLinkText”
 Webdriver API is much more Object oriented than RC


What is Webdriver in Selenium


 public static void main(String aa[])
 {
  int i=1,j=1;
  System.out.print(i+ ",");
  System.out.print(j+ ",");
  while(i<100)
  {
   i=i+j;
   if(i<100)
   {
   System.out.print(i+ " , ");
   }
   j=i-j;
   
  }
    }

Fabonacci series in Java


 public static void main(String aa[])
 {
  String name = "hello";
  String s_str="hel";
   int flag=0;
  int len, len1,m;
        len= name.length();
        len1= s_str.length();
        char arr[]=new char[len];
        char s_arr[] = new char[len1];
        for(int k=0;k<len;k++)
        {
         arr[k]= name.charAt(k);
        }
        for(int k=0;k<len1;k++)
        {
         s_arr[k]= s_str.charAt(k);
        }
        for(int i=0;i<len;i++)
        {
         if(arr[i]==s_arr[0])
         {
          m=i;
            for(int j=0;j<len1;j++)
               {
             
              if(s_arr[j]==arr[i])
              {
               flag=flag+1;
                  i=i+1;  
              }
               }
              if(flag==len1)
              {
               System.out.println("Sub Srting Exists");
              
              }
              else
           {
            flag=0;
               i=m;
           }
         }
        }
        
    }
}

Check Substring in Java


public class Test1 {

 public static void main(String aa[])
 {
  String name = "hello";
  
  int len;
        len= name.length();
        char arr[]=new char[len];
        for(int i=0;i<len;i++)
        {
         
         arr[i]=name.charAt(i);
        }
        for(int i=len-1;i>=0;i--)
        {
         System.out.print(arr[i]);
        }
 }
}

Reverse a String in Java using Array


public class Test1 {

 public static void main(String aa[])
 {
  String name = "nitin";
  String n_ame="";
  int len;
        len= name.length();
        for(int i=(len-1);i>=0;i--)
        {
         n_ame = n_ame +name.charAt(i);
        }
        if(name.equals(n_ame))
        {
         System.out.println("This is a palindrome");
        }
 }
}

Check for palindrome in Java


public class Test1 {

 public static void main(String aa[])
 {
  String name = "hello";
  int len;
        len= name.length();
        for(int i=(len-1);i>=0;i--)
        {
         System.out.print(name.charAt(i));
         }
 }
}

Reverse a String in Java


Both methods are used for page submission

GET :  Data is processed/encoded(by browser) in URL as a name value pair 
           Old browser has restriction of URL to 255 characters
           Can be easily traced in the history of web browser.
           Mainly used when we want to retrieve data.
           As data transferred in URL so we need to do extra care of some characters like space and & etc,
      
POST : In post request, data is processed as a message body
             Here we have not restriction of data size.
             Mainly use when we need to submit, update large data.


Difference between GET and POST


CaptureScreenshot
      Supported in all browsers
      Take screenshot of display screen with OS controls like start button etc
      Take only 1 argument(file name with path)
    
 
 CaptureEntirePageScreen
      Supported on Mozilla for IE need addon.
      Take screenshot of complte AUT page, irrespective to scroll bar etc.
      Take 2 arguments(file path , background colour)


Difference between CaptureScreenshot and CaptureEntirePageScreenshot


SET IN JAVA ( Belongs to Collection API) – import java.utils.*;


Set is used to hold multiple data.
Can hold only unique data
Can hold max 1 null
Implements Collection interface
By default set can hold any type of data

                                                         3 type of Set

HASH set :: Elements are not ordered , fast
Tree Set :: Elements are in sorted ordered, slow
LinkedSet "" Between of Hash and Tree, elements are ordered and fast as well



Set in Java


Ant is an open source tool for creating builds, it is used to automation repetitive task which we do while creating build, like compiling source code, creating jars javadoc etc.

Ant uses a xml file for configuration.

This xml file contain Target,
 Target means that action/steps need to be performed, it can have  multiple dependent/independent targets for example if a Target A is dependent to Target be then Ant will execute Target B before A.

We can also specify main Target. Main target means target that will be execute per default this main target is dependent to other target that Ant will  execute other targets then this main target.

Apache Ant ( Build Automation Tool)

1 Thread.sleep() :  This is the way by which we can hold the execution of script for the predefined time
 It is forcefully wait for the given time

2 Implicitely Wait
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));

The ImplicitWait will tell the webdriver to wait  certain duration when trying to find the element, this will be useful when certain elements on the webpage will not be available immediately and needs some time to load.
This will work only with find element commands

3 pageLoadTimeout()
By this we can wait for a certain period of time to wait for a page to load.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);

4 Wait for Element Present: By this we can wait until a element present or application state to be changes

WebDriverWait wait = new WebDriverWait(firef, 10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@id=':gp']/div/div")));



Implementation of Wait in Selenium


Working with LIST AND DROPDOWN in selenium

WEBDRIVER

1st Way         // To Work on dropdown or List we need to create object of Select class
  Select dateselect =  new Select(driver.findElementById("f_mydata"));
  
  // Here we have 3 options to select an element 
  dateselect.selectByIndex(1);
  dateselect.selectByValue("15");
  dateselect.selectByVisibleText("MyData");


2nd Way         // Just Write code in 1 line rather than writing in 2 differnt line

                     new Select(driver.findElementById("f_mydata")).selectByIndex(0);



RC


  // Working with List
  selenium.addSelection("ElementLocator", "Value");
  // Working with Dropdown
  selenium.select("ElementLocator", "Value");



Working with LIST AND DROPDOWN in selenium

// RemoteControlConfiguration class is used to set configuration
  // of server like, setting port or single window etc
  RemoteControlConfiguration rc = new RemoteControlConfiguration();
  rc.setPort(4445);
  rc.setSingleWindow(true);
 
  // Selenium Server class is used to start server
  // pass RemoteControlConfiguration object while creating object
  SeleniumServer ss = new SeleniumServer(rc);
 
  // boot method is to apply setting to server
  ss.boot();
 
  // start method is to start server
  ss.start();
  

Starting Selenium Server through Code

         Generate TestNg.xml Dynamically

We can create a virtual testng.xml file yourself. In order to do this, you can use the classes found the packageorg.testng.xml: XmlClass, XmlTest, etc... Each of these classes correspond to their XML tag counterpart.

For example, suppose you want to create the following virtual file:
<suite name="TmpSuite" >
  <test name="TmpTest" >
    <classes>
      <class name="test.failures.Child"  />
    <classes>
    </test>
</suite>
You would use the following code:

XmlSuite suite = new XmlSuite();
suite.setName("TmpSuite");

XmlTest test = new XmlTest(suite);
test.setName("TmpTest");
List<XmlClass> classes = new ArrayList<XmlClass>();
classes.add(new XmlClass("test.failures.Child"));
test.setXmlClasses(classes) ;


And then you can pass this XmlSuite to TestNG:

List<XmlSuite> suites = new ArrayList<XmlSuite>();
suites.add(suite);
TestNG tng = new TestNG();
tng.setXmlSuites(suites);
tng.run();


Program
package org.nitin;

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

import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.TestListenerAdapter;
import org.testng.TestNG;
import org.testng.annotations.Test;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;

public class TCase1 {

 @Test
    public void TCase()
     {
  System.setProperty("webdriver.chrome.driver","C:\\Documents and Settings\\Administrator\\My Documents\\Downloads\\chromedriver_win32_2.1\\chromedriver.exe");
   ChromeDriver f = new ChromeDriver();
   f.get("http://mail.in.com");
   f.findElementById("f_id").sendKeys("uname");
   f.findElementById("f_pwd").sendKeys("pass");
   f.findElementByClassName("signin");
   XmlSuite suite = new XmlSuite();
   suite.setName("OMS");
   XmlTest test1 = new XmlTest(suite);
   test1.setName("TCase1");
   List<XmlClass> classes = new ArrayList<XmlClass>();
   classes.add(new XmlClass("org.nitin.TCase1"));
   List<XmlSuite> suite_a = new ArrayList<XmlSuite>();
   suite_a.add(suite);
   TestNG tng = new TestNG();
   tng.setXmlSuites(suite_a);
   tng.run();
   /*XmlSuite suite = new XmlSuite();
   suite.setName("OMS");
   
   XmlTest test = new XmlTest(suite);
   test.setName("Case1");
   List<XmlClass> classes = new ArrayList<XmlClass>();
   classes.add(new XmlClass("org.nitin.TCase1"));
   test.setXmlClasses(classes) ;
   List<XmlSuite> suites = new ArrayList<XmlSuite>();
   suites.add(suite);
   TestNG tng = new TestNG();
   tng.setXmlSuites(suites);
   tng.run();
 */

  }

}


Generate TestNg.xml Dynamically

                                         Working with Log4J API
Log4j as this is an open source logging library
Log4j is built with three main concepts: 
1.       loggers
2.       appenders
3.       Layouts.  

Logger is the main engine which sends the logging requests to appender.  Appender might be a console, a log file, printer, etc.  Layout is the formatting of the log output. 
Step 1) Include log4j jar in build path

2) Create log4j.properties in the src folder 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");
            
    }
}

Log4j API for creating logs in Selenium

Pri
Annotation name
Documentation
1
@BeforeSuite
Annotates methods that will be run before any method in a given is run.
2
@BeforeGroups
Annotates methods that will be run before the first method in any of the specified groups is run.
3
@BeforeClass
Annotates methods that will be run before the first method on the current test class is run.
4
@BeforeTest
Annotates methods that will be run before any method in a given is run.
5
@BeforeMethod
Annotates methods that will be run before each test method.
6
@AfterMethod
Annotates methods that will be run after every test method.
7
@AfterTest
Annotates methods that will be run after all the test methods in a given have been run.
8
@AfterClass
Annotates methods that will be run after the last test method on the current class is run.
9
@AfterGroups
Annotates methods that will be run after the last test method belonging to the groups specified in its value attribute has been run. The annotated method is automatically put into these specified groups.
10
@AfterSuite
Annotates methods that will be run after all the test methods in a given have been run.


Annotations in TestNg

Annotation
Description
@Test public void method()
Annotation @Test identifies that this method is a test method.
@Before public void method()
Will perform the method() before each test. This method can prepare the test environment, e.g. read input data, initialize the class)
@After public void method()
Test method must start with test
@BeforeClass public void method()
Will perform the method before the start of all tests. This can be used to perform time intensive activities for example be used to connect to a database
@AfterClass public void method()
Will perform the method after all tests have finished. This can be used to perform clean-up activities for example be used to disconnect to a database
@Ignore
Will ignore the test method, e.g. useful if the underlying code has been changed and the test has not yet been adapted or if the runtime of this test is just to long to be included.
@Test(expected=IllegalArgumentException.class)
Tests if the method throws the named exception
@Test(timeout=100)
Fails if the method takes longer then 100 milliseconds

Annotations in Junit

                                ]


                            HOW TO INSTALL TESTNG in ECLIPSE

1à Open Eclipse.

2à Go to HELPà INSTALL NEW SOFTWARE

3à Add following URL in first field, click on ADD, give name.




4à It will display TestNG, click Next, Finish.



It will take few minutes then ask for restart of eclipse then install TestNG on Eclipse.


                                To check TestNG installed or not.

Go to Windowsà Show Viewà Othersà Java      (Here it should display TestNg.)




                        HURRAY………………..TESTNG is installed successfully.


Install TestNg in Eclipse

                                               Dataprovider Annotation in TestNG
Dataprovider annotation is mainly used for parameterization in Test Cases
We have a define a method under the data provide annotation, here we pass test data
Data provider method return of 2 dimension object array
We can pass this data returned by data provider in our test cases, function will execute in loop for each row of returned 2 dimension array

Here is the example
package org.abc;

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class Case1 {

     
@Test(dataProvider="Dp1")
   public void TCase(String uname, String pass)
    {
      System.setProperty("webdriver.chrome.driver","C:\\Documents and Settings\\Administrator\\My Documents\\Downloads\\chromedriver_win32_2.1\\chromedriver.exe");
       ChromeDriver f = new ChromeDriver();
       f.get("http://mail.in.com");
       f.findElementById("f_id").sendKeys(uname);
       f.findElementById("f_pwd").sendKeys(pass);
       f.findElementByClassName("signin");
      }
     
@DataProvider(name="Dp1")
    public Object[][] DataRe()
    {
         Object arr[][]={{"unam1","pass1"},
                                   {"uname2","pass2"},
                                   {"uname3","pass3"}};
       
    return(arr);
    }
}



Parameterization in TestNg