Friday 15 August 2014

Array Functions in QTP


1)Array() in QTP


-> The Array function returns a  variant containing an array.

-> The first element of array index is zero.



Syntax

Array(arglist)


Here,

arglist - Required. Its contains value seperated by comma. and values represented as array.


Example:


a=array(3,5,8)
msgbox a(1)


Here the values are,

a(0)=3
a(1)=5
a(2)=8




2) Filter() in QTP

-> Filter function used to create another array variable from another array variable by using some filter creteria.


Syntex:

Filter(Source_arrayvariable,value[,include[,compare]])


Here,


Source_arrayvariable = Required. one dimensional array. This is source string

value = Required. Used for search string in Source_arrayvariable. Its case- sensitive.

include = Optional, Boolean value
 True = Default. Return String as per matched with above given value.
 False = Return string that is not matched as per above given value.
Compare = Optional. Specifies the string comparison to use.
0 = vbBinaryCompare - Perform a binary comparison
1 = vbTextCompare - Perform a textual comparison



Return Values:

Return new array with values from Source_arrayvariable as per the filter creteria.



Example:


a=Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
b=filter(A,"Sun",true)
For each str  In b
print str
Next



O/P
Sunday




3) IsArray() function in QTP

-> IsArray() returns boolean value and its indicates that given variable is array variable or normal variable.

->  If the variable is an array, it returns True, otherwise, it returns False.


Syntex :

IsArray(variable)

Variable : Required. Any variable


Return type:

True : If the variable is an array
False : If the variable is NOT an array,


Example:

a=Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
print msgbox(IsArray(A))


O/P

TRUE



4) Join() funtion in QTP

The Join() function used to join all elements from array.


Syntex:

Join(Array_Variable[,delimiter])

Here,

Array_Variable = Required. one dimensional array variable name.
delimiter = optional, used to add delemiter char with end of all element(Sub String) in given array variable.


Return Types:

Its return String which contains all number of element (substrings) in an array.


Example :

a=Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
print join(a,"#")

o/p

Sunday#Monday#Tuesday#Wednesday#Thursday#Friday#Saturday



5) Split Function in QTP


Split function used to zero based, one dimensional array that contains specified number of sub string.


Syntax:

Split(expression[,delimiter[,count[,compare]]])

Here,


6) LBound Function in QTP

Returns the smallest subscript for the indicated dimension of an array

LBound(arrayname[,dimension])





7) UBound Function in QTP

Returns the largest subscript for the indicated dimension of an array


UBound(arrayname[,dimension])

String Function in QTP



1) Instr function in QTP

Instr returns first occurance of the string1 with in another string2.

Syntex:

Instr([start,] String1,String2, [compare])

Here,

Start   = optional, Postion of the start search from String1
String1 = Required, This is main String.
String2 = Required, This is sub String to be search in String2
Compare = Optional, Specifies the string comparison to use. Default is 0

 Can have one of the following values:

 0 = vbBinaryCompare - Perform a binary comparison
     1 = vbTextCompare - Perform a textual comparison



Return Values :

0      -> If String1 is ""
0       ->  If String2 is not found
0           -> if start > len(String1)
Null       -> If String1 is Null
Null       -> If String2 is Null
Start val   -> If Strin2 is ""
position val-> If string2 is found within string1



Example :

Instr(1,"The QTP Tutorial","T")

o/p 1


2) InStrRev function in QTP

InstrRev returns first occurance of the String1 with in another string. The search begin starts from end of the string. But position returned counts from the beginning of the string.


Syntex:

InStrRev(String1,String2[,start],[compare])

Here,

String1 = Required, This is main String.
String2 = Required, This is sub String to be search in String2
Start   = Optional. Specifies the starting position for each search. The search begins at the last character position by default (-1)
Compare = Optional. Specifies the string comparison to use. Default is 0

 Can have one of the following values:

 0 = vbBinaryCompare - Perform a binary comparison
     1 = vbTextCompare - Perform a textual comparison



Return Values :

0      -> If String1 is ""
0       ->  If String2 is not found
0           -> if start > len(String1)
Null       -> If String1 is Null
Null       -> If String2 is Null
Start val   -> If Strin2 is ""
position val-> If string2 is found within string1


Example :

Instr(1,"The QTP Tutorial","a")

o/p 11



3) Lcase function in QTP

Converts specified string to lower case.

Syntex:

Lcase(String)

Here,

String = Required, string to be change lower case.



4) Ucase function in QTP

Converts specified string to upper case.

Syntex:

Ucase(String)

Here,

String = Required, string to be change upper case.







5) Left function in qtp

Left function used to returns number of characters from left side of the string.

Syntex:

Left(string1,length)

Here,

String1 = Required, Main string used to returns character from.
lenght  = Required, Specifies how many characters to return from left side of the string.


Return values

if length = 0      -> Returns Empty String ""
if length >= len(String) -> Returns full String
if lenght < len(string)    -> Returns number of character from left side


Example :

left("This is QTP tutorial",11)

o/p "This is QTP"





6) Right function in qtp

Right function used to returns number of characters from right side of the string.

Syntex:

Right(string1,length)

Here,

String1 = Required, Main string used to returns character from.
length  = Required, Specifies how many characters to return from right side of the string.


Return values

if length = 0      -> Returns Empty String ""
if length >= len(String) -> Returns full String
if lenght < len(string)    -> Returns number of character from right side


Example :

left("This is QTP tutorial",11)

o/p "TP tutorial"




7) Len Function in QTP

Len function used to returns the number of characters from given string.

Syntex:

Len(String)

Here,

String = Required

Example:

len("qtp")

o/p 3



8) Ltrim function in QTP

Ltrim Function used to remove spaces from left side.

Syntex:

Ltrim(String)

Here,

String = Required

Example:

len("qtp  ")

o/p qtp


9) Ltrim function in QTP

Rtrim Function used to remove spaces from right side.

Syntex:

Rtrim(String)

Here,

String = Required

Example:

len("  qtp")

o/p qtp



10) Trim function in QTP

Trim Function used to remove spaces from both side.

Syntex:

Ltrim(String)

Here,

String = Required

Example:

len("  qtp  ")

o/p qtp   



11) Mid function in QTP

Mid function returns number of characters from given string

Syntax

Mid(string,start[,length])

Here,

String = Required, The string which char can be returned
Start  = Required, Specifies the starting position.
lenght = optional, the number of characters to be returned.

Return values,

If start > len(String) = Return empty string ("")

Ex:

mid("This is QTP Tutorial",1,4)

o/p  This




12) Replace function in QTP

Replace the specified number of string with in one another.

Syntex:

Replace(String,Find,ReplaceWith[,Start[,Count[,compare)

Here,

String      = Required. Main String used to replace
Find    = Required, THis is String which is find in the main String for replacement
ReplaceWith = Required, Substring which is going to replace in main string.
Start       = Optional, From which postion from main string going to search and replace. Default is 1. All characters before the start position will be removed.
count       = Optional, number of replacement in Main String. Default value is -1, which means make all possible substitutions
compare       = Optional, Specifies the string comparison to use. Default is 0

 Can have one of the following values:
 0 = vbBinaryCompare - Perform a binary comparison
        1 = vbTextCompare - Perform a textual comparison   



Example :

Replace("This is a beautiful day!","i","##",2,2)

o/p  "h##s ##s a beautiful day!"




13) Space function in QTP

The Space function returns a string that consists of a specified number of spaces.


Syntax

Space(number)


Here,

number    = Required. The number of spaces you want in the string


Example

space(3)

o/p "   "



14) Strcomp function in QTP

The Strcomp function used to comapare the two string and return the values as per the result of comparison.

Syntax:

StrComp(string1,string2[,compare])

String1 = Required.
String2 = Required.
compare = Optional, Specifies the string comparison to use. Default is 0

 Can have one of the following values:
 0 = vbBinaryCompare - Perform a binary comparison
        1 = vbTextCompare - Perform a textual comparison


Return values,

-1    = if string1 < string2
0    = if string1 = string2
1    = if string1 > string2
Null    = if string1 or string2 is Null





15) String function in QTP

The String function returns the string with contains given number of continuous character.

Syntex:

String(Number,character)


Here,

number     = Required. The length of the returned string
character = Required. The character that will be repeated


Return values,

if character = "more than one letter"  -> It consists first letter of that string.

Example:

String(4,H)   ->  O/P  HHHH
String(4,"

How to use FOR EACH loop in QTP



-> FOR EACH loop used to execute every single element or item in a group.

-> Normally its used to like

1) Every single element in an Array
2) Every single files in a folder
3) Every character in a String

in these type of situation we can use FOR EACH loop.

Syntex

For Each [Item] In [Group]
   [loopBody]
Next [Item]


Example :

a=Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")

For each str In a
print str
Next

output :

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday



From above example, we print the every element in array.


GetAttribute Method in Selenium





-> This method used to Gets the value of the specified attribute for this Web element.

Syntex:

WebElement.GetAttribute("Attribute_Name")

o/p

Returns the value of the Attribute name.



Example:



Source :

<a id="link1" href="http:gmail.com">
<span lang="LBLSHOVIDEOS">Selenium</span></a>


Script :


String attr1=driver1.findElement(By.linkText("Selenium")).getAttribute("id");
System.out.println("Attribute ID Value="+attr1);

String attr2=driver1.findElement(By.linkText("Selenium")).getAttribute("href");
System.out.println("Attribute HREF Value="+attr2);



O/P :

Attribute ID Value= Link1

Attribute HREF Value=http:gmail.com

Data driven testing in TestNG (Using @DataProvider annotaion)





-> @DataProvider annotations in TestNG is important for data driven framework in selenium.

-> @DataProvider Annotation of testng framework provides us a facility of storing and preparing data set In method.

-> Task for @DataProvider Annotation is supplying data for test method. That means we can configure data with in the @DataProvider annotations and use those data inside the @Test methods.

-> @dataprovider method should return an Object[][] with data.

-> we have to create two dimensional array in @DataProvider annotation data to stored the data.



Example:


Bellow given example will retrieve userid and password one by one from @DataProvider annotated method and will feed them In LogIn_Test(String Usedid, String Pass) one by one. Run this example In your eclipse and observe result.



public class Sample_Login {

 WebDriver driver = new FirefoxDriver();


 @BeforeTest
    public void setup() throws Exception {
         driver.manage().window().maximize();
         driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
         driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
    }


  @AfterTest
 public void tearDown() throws Exception {
   driver.quit();
     }


 //This method will return two dimensional array.
 //This method behaves as data provider for LogIn_Test method.

 @DataProvider

 public Object[][] LoginCredentials(){

  //Created two dimensional array with 4 rows and 2 columns.
  //4 rows represents test has to run 4 times.
  //2 columns represents 2 data parameters.

 Object[][] Cred = new Object[4][2];

  Cred[0][0] = "UserId1";
  Cred[0][1] = "Pass1";

  Cred[1][0] = "UserId2";
  Cred[1][1] = "Pass2";

  Cred[2][0] = "UserId3";
  Cred[2][1] = "Pass3";

  Cred[3][0] = "UserId4";
  Cred[3][1] = "Pass4";
  return Cred; //Returned Cred
 }



 //Give data provider method name as data provider.
 //Passed 2 string parameters as LoginCredentials() returns 2 parameters In object.

 @Test(dataProvider="LoginCredentials")

 public void LogIn_Test(String Usedid, String Pass){
   driver.findElement(By.xpath("//input[@name='userid']")).clear();
   driver.findElement(By.xpath("//input[@name='pswrd']")).clear();
   driver.findElement(By.xpath("//input[@name='userid']")).sendKeys(Usedid);
   driver.findElement(By.xpath("//input[@name='pswrd']")).sendKeys(Pass);
   driver.findElement(By.xpath("//input[@value='Login']")).click();
   String alrt = driver.switchTo().alert().getText();
   driver.switchTo().alert().accept();
   System.out.println(alrt);
  }
}




testng.xml file to run this example Is as bellow.


<suite name="Simple Suite">
 <test name="Simple Skip Test">
  <classes>
   <class name = "Testng_Pack.Sample_Login"/>
  </classes>
 </test>
</suite>




After run the above code, the user id and password entered one by one in above URL.

Selenium WebDriver Parallel Tests Execution Using TestNG - @Parameters




-> Browser compatibility testing Is most Important thing for any web application and generally you have to perform browser compatibility testing before 1 or 2 days of final release of application. In such a sort time period, you have to verify each Important functionality In every browsers suggested by client.


-> If you will go for running your all webdriver tests In each browsers one by one then It will take too much time to complete your test and you may not complete It before release.

-> In such situation, Running your tests In all required browsers at same time will helps you to save your time efforts.

-> The above situation solved in selenium by using @Parameters annotation in TestNG framework.



Parallelism In TestNG


We can configure our TestNG.xml file in such a way to run our test suite or tests or methods in seperate browsers Is known as parallelism In TestNG.


ParellelTestng.java


package TestNG_Package;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestNG_Test1 {

 private  WebDriver driver1=null;

  @BeforeClass
  @Parameters ({"browser"})

  public void setup(String browser)
 {
   if (browser.equals("FFX"))
  {
     System.out.println("Test Starts Running In Firefox Browser.");
     driver1 = new FirefoxDriver(); 
    }
  else if (browser.equals("CRM"))
  {
     System.out.println("Test Starts Running In Google chrome.");
     System.setProperty("webdriver.chrome.driver",  "D:\\chromedriver_win32_2.3\\chromedriver.exe");
     driver1 = new ChromeDriver(); 
   }
   driver1.manage().window().maximize();
   driver1.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
  }


 @AfterClass
 public void closebrowser()
 {
    driver1.quit();
 }


 @Test
 public void MethodOne() {

  String a= "Selenium";
  if(a.equals("Selenium")
   throw new SkipException("Skipped");

  String title = driver1.getTitle();
  System.out.println("title"+title);   
 }



 @Test
 public void MethodTwo() {
  String title = driver1.getTitle();
  System.out.println("title"+title);   
 }


}




testng.xml

<suite name="webDriver" parallel="tests">

 <test name="Test In FireFox" >
    <parameter name="browser" value="FFX" />
    <classes>
      <class name="Testng_Pack.Test_Parallel" />
    </classes>
  </test>

   <test name="Test In Google Chrome" >
    <parameter name="browser" value="CRM"></parameter>
    <classes>
      <class name="Testng_Pack.Test_Parallel"></class>
    </classes>
  </test>

</suite>




From above example we can run same test in both Chrome and FireFox at same time.

From above Testng.xml file

-> parallel="tests" which inside <suite> tag will instruct TestNG to consider method of each <test> tag as seperate Thread. that Means If you wants to run your test In 2 different browsers then you need to create two <test> blocks for each browser Inside testng.xml file.

-> Inside each <test> tag block, define one more tag "parameter" with same name(In both <test> block) but with different values.Its used to pass in ParellelTestng.java method.



From ParellelTestng.java

-> Here we are used @Parameters annotation to pass parameter in method.Values of this parameter will be feed by testng.xml file.

-> If condition will check that value to decide which driver to use for test. This way, example testng.xml file will feed two values(FFX and CRM) In parameter so It will open Firefox and Google chrome browsers and run test In both browsers

How To Skip WebDriver Test In TestNG





We can skip the execution from perticular test by using throw new SkipException() exception. THis is TestNG exception.

Sometimes you need to check some condition like If some condition match then skip test else perform some action In your webdriver test. In this kind of situation, you can use SkipException() exception.


Consider below example




package TestNG_Package;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestNG_Test1 {
WebDriver driver1=new FirefoxDriver();
@BeforeMethod
public void OpenBrowser(){
driver1.get("http://google.com");
driver1.manage().window().maximize();
}
@AfterMethod
public void CloseBrowser(){
driver1.quit();
}
@Test
public void MethodOne() {

String a= "Selenium";
if(a.equals("Selenium")
throw new SkipException("Skipped");

String title = driver1.getTitle();
System.out.println("title"+title);   
}



@Test
public void MethodTwo() {
String title = driver1.getTitle();
System.out.println("title"+title);   
}


}



o/p

MethodOne Skipped due to SkipException()
MethodTwo executed


From above example if execution throw SkipExeption() means the rest of the commands inside the method wont get executed. Its skipped from current method and control goes to next method.

Include/Exclude Selenium WebDriver Test Package From Test Suite Using testng.xml




We can include or exclude selenium webdriver from test suite using below steps


1) Create new package and classes as below

TestNGOnePack(package) -> BaseClassOne.java, ClassOne.java, ClassTwo.java
TestNGTwoPack(package) -> ClassOne.java, ClassTwo.java
TestNGThreePack(package) -> ClassOne.java, ClassTwo.java


2) Include perticular package from test suite


<suite name="Suite One">
  <test name="Test One" >
     <packages>
        <package name=".*">
           <include name="TestNGOnePack" > </include>
        </package>
     </packages>
  </test>
</suite>


We can execute only "TestNGOnePack", "TestNGThreePack" package from this execution. We exclude "TestNGTwoPack" package from execution.


3) Exclude Perticular package from test suite execution



<suite name="Suite One">
  <test name="Test One" >
     <packages>
        <package name=".*">
           <exclude name="TestNGOnePack" > </exclude>
        </package>
     </packages>
  </test>
</suite>

We can execute only  "TestNGTwoPack","TestNGThreePack" package from this execution. We exclude "TestNGOnePack" package from execution.So its not get execute.

Include/Exclude Only Selected Test Methods from class Test Suite Using testng.xml





Its possbile we can include or exclude selected test method from any class.


1) Create new package and classes as below

TestNGOnePack(package) -> TestNG_Test1.java

2) And BaseClassOne.java have before methods

TestMethod1(),TestMethod2(),TestMethod3()



3) Include test method from class for execution


<suite name="TestNG_Suite">
<test name="TestNG_Test">
<classes>
<class name="TestNGOnePack.TestNG_Test1"></class>
<methods>
<include name="TestMethod1"> </include>
<include name="TestMethod2"> </include>
</methods>
</classes>
</test>
</suite>



From above example, we execute only TestMethod1 and TestMethod2 in execution. But the TestMethod3 is not executed.




4) Exclude Test Method from class for execution.


<suite name="TestNG_Suite">
<test name="TestNG_Test">
<classes>
<class name="TestNGOnePack.TestNG_Test1"></class>
<methods>
<exclude name="TestMethod1"> </exclude>   
</methods>
</classes>
</test>
</suite>



From above example, we execute only TestMethod2(),TestMethod3() in execution. But TestMethod1() is exclude from execution. So its not executed.

Configure testng.xml In Eclipse For Selenium WebDriver To Run All Or Specific Package



TestNG is very useful and powerful framework for selenium webdriver. We need to configure our tests based on our requirements or test scenarios.


Create new package and classes as below


TestNGOnePack(package) -> BaseClassOne.java, ClassOne.java, ClassTwo.java
TestNGTwoPack(package) -> ClassOne.java, ClassTwo.java
TestNGThreePack(package) -> ClassOne.java, ClassTwo.java



Configure testng.xml to run selected packages from all packages of webdriver project in single test suite


From three packages, I wants to run only two packages -> "TestNGTwoPack" and "TestNGThreePack". For that we need to configure testng.xml as bellow.

<suite name="Suite One">
 <test name="Test One" >
  <packages>
   <package name="TestNGTwoPack" />
   <package name="TestNGThreePack" />
  </packages>
 </test>
</suite>


In above example <packages> tag used to describe group of packagesand  is used to add specific package in our test suite.

So when you run above testng.xml file, It will run only targeted two packages(TestNGTwoPack, TestNGThreePack). Other (TestNGOnePack)package(s) will be excluded from execution.


Configure testng.xml to run all packages of project in single test suite

If you wants to run all packages of your project, you can configure your testng.xml using wildcard(.*) with package tag as bellow.

<suite name="Suite One">
 <test name="Test One" >
  <packages>
   <package name=".*" />  
  </packages>
 </test>
</suite>

Configure testng.xml In Eclipse For Creating Web Driver test using classes from different packages.



For example we create new packages and classes using below steps,

Step 1. Create package = "TestNGOnePack" with classes = BaseClassOne.java, ClassOne.java and ClassTwo.java

Step 2. Create package = "TestNGTwoPack" under same project and add ClassOne.java and ClassTwo.java files

Step 3. Create package = "TestNGThreePack" under same project and add ClassOne.java and ClassTwo.java file



Here i dont want to execut all classes from all packages. I need some selected classes from selected packages. like like TestNGOnePack.ClassOne, TestNGTwoPack.ClassTwo, TestNGThreePack.ClassOne and TestNGThreePack.ClassTwo


Here we need to configure testng.xml file as below

<suite name="Suite One">
 <test name="Test One" >
  <classes>
   <class name="TestNGOnePack.ClassOne" />
   <class name="TestNGTwoPack.ClassTwo" />
   <class name="TestNGThreePack.ClassOne" />
   <class name="TestNGThreePack.ClassTwo" /> 
  </classes>
 </test>
</suite>


This way we can configure our test suite using only specific class from different packages

Configure testng.xml In Eclipse For Create single or multiuple class run under single or multiple test.



We can create any number of class may run under in any number of test in same execution by using testng.xml file.


For Example:


1. BaseClassOne.java
package TestNGOnePack;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;

public class BaseClassOne {

    public static WebDriver driver = new FirefoxDriver();

    //@BeforeSuite annotation describes this method has to run before all suites
    @BeforeSuite
    public void setup() throws Exception {
         driver.manage().window().maximize();
         driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
         driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
    }

    //@AfterSuite annotation describes this method has to run after execution of all suites
    @AfterSuite
         public void tearDown() throws Exception {
         driver.quit();
    }
}
Above class will be used as base class to initialize and close webdriver instance.


2. ClassOne.java
package TestNGOnePack;

import org.testng.annotations.Test;

public class ClassOne extends TestNGOnePack.BaseClassOne{

 //@Test annotation describes this method as a test method
 @Test
  public void testmethodone() {
    String title = driver.getTitle();
    System.out.print("\nCurrent page title is : "+title);
    String Workdir = System.getProperty("user.dir");
    String Classpackname = this.getClass().getName();
    System.out.print("\n'"+Workdir+" -> "+Classpackname+" -> testmethodone' has been executed successfully");
  }
}

Above ClassOne is inherited from BaseClassOne.



3. ClassTwo.java
package TestNGOnePack;

import org.testng.annotations.Test;

public class ClassTwo extends TestNGOnePack.BaseClassOne{

 //@Test annotation describes this method as a test method
 @Test
  public void testmethodone() {
  driver.navigate().to("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
  String title = driver.getTitle();
  System.out.print("\nCurrent page title is : "+title);
  String Workdir = System.getProperty("user.dir");
  String Classpackname = this.getClass().getName();
  System.out.print("\n'"+Workdir+" -> "+Classpackname+" -> testmethodone' has been executed successfully");
  }
}




We can create above two class as Classone.java and ClassTwo.java. Then we create testng.xml file as below for run under same test or multiple test.


Configure testng.xml to run two classes in one test

<suite name="Suite One" >
 <test name="Test One" >
  <classes>
   <class name="TestNGOnePack.ClassOne" />
   <class name="TestNGOnePack.ClassTwo" />
  </classes>
 </test>
</suite>


When test execuion get complete we can see the both class are run under same test.



Configure testng.xml to run two classes in two tests

.
Now if you wants to run both classes as separate test then you have to configure your testng.xml file as bellow.



<suite name="Suite One" >
 <test name="Test One" >
  <classes>
   <class name="TestNGOnePack.ClassOne" /> 
  </classes>
 </test>
 <test name="Test Two" >
  <classes>
   <class name="TestNGOnePack.ClassTwo" />
  </classes>
 </test>
</suite>

Configure testng.xml In Eclipse For Creating And Running WebDriver Test Suit Using testng.xml File



Usage Of testng.xml File

In TestNG framework, We need to create testng.xml file for below purpose

-> To create and handle multiple test classes.

-> we can configure our web test as per our needs in testng.xml file.

-> we can set dependency

-> include or exclude any method or any classes or any package.

-> Set Priority



Creating TestNG.xml file



1) For creating testNG.xml file, we need to right click on project -> New-> file -> open new file wizard

2) In New File wizard select project and give file name as "TestNG.xml" and then click Finish button.

3) It will add TestNG.xml file under our current project.

4) Then add below lines in TestNG.xml file (Select Source tab for type below code in Eclipse)


<suite name="TestNG_Suite">
<test name="TestNG_Test">
<classes>
<class name="TestNG_Package.TestNG_Test1"></class>
</classes>
</test>
</suite>



Here,

-> <suite> :

 suite tag defines the TestNG suite. You can give any name to your suite using 'name' attribute. In above given example, We have given "Suite One" to our test suite.


-> <test> :

test tag defines the TestNG test. You can give any name to your test using 'name' attribute. In above given example, We have given "Test One" to our test.


-> <classes> :

classes tag defines multiple class. We can multiple test class under classes tag. In our example we have only one class.


-> <class> :

class tag defines the class name which you wants to consider in test execution.


Example :

In above given example, we have defined name="TestNG_Package.TestNG_Test1"

Here 'TestNG_Package' describes package name
and 'TestNG_Test1' describes class name.

So in above example we are going to run only one class.



5) Running TestNG.xml file


Right click on testng.xml file -> Run As -> Select TestNG Suite

It will start execution of Test_Test1 class.



6)  View test execution HTML report generated by TestNG


- Right click on Project named as "TestNG_Project and select Refresh.

- then Folder with name = "test-output" will be created under your project folder.

- Explorer that "test-output" folder. then we can see the "index.html" file.

- Right click on "index.html" file then select open with -> Web browser - To see the HTML report in Eclipse.

Thursday 14 August 2014

Steps for Create and Run TestNG testcase in Eclipse



Let me describe you steps of writing your first test case with TestNG.


1) Create New Project and New package for TestNG

- File -> New -> Java Project -> give new project name as "TestNG_Project"

- Richt click on "src" inside project name as "TestNG_Project" -> New -> Package -> give name as TestNG_Package



2) Add TestNG library


- Goto your project's Properties -> Java Build Path -> Libraries Tab.

- Click on Add Library button -> Select TestNG from Add Library popup and then click on Next and Finish buttons.

- And then verify it will add TestNg library in your project under library tab. Now click on OK button to close that window.



3) Create TestNG Class

- TO create TestNG class is different steps compare to create normal class in java project. Follow below steps to create TestNG class

- Right click on package as TestNG_package and click -> new -> other - it will open new wizard window

- Select TestNG from new wizard window and click on next button.

- on next screen add class name as "TestNG_Test1" and click finish.

- It will as new class as "TestNG_class1" under TestNG_Project with below coding.


package TestNG_Package;


public class TestNG_Test1 {

@Test
public void f(){
}
}




4) Add/write sample webdriver test script.

Write your own test script or add bellow given script in TestNG class file.




package TestNG_Package;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestNG_Test1 {
WebDriver driver1=new FirefoxDriver();
@BeforeMethod
public void OpenBrowser(){
driver1.get("http://google.com");
driver1.manage().window().maximize();
}
@AfterMethod
public void CloseBrowser(){
driver1.quit();
}
@Test
public void f() {
String title = driver1.getTitle();
System.out.println("title"+title);   
}
}





5)  Run Webdriver test script with TestNG


- Go to Run -> Run As -> And Click on TestNg Test

- It will run your webdriver test with TestNG.

- we can the result after complete the execution.



6)  View test execution HTML report generated by TestNG


- Right click on Project named as "TestNG_Project and select Refresh.

- then Folder with name = "test-output" will be created under your project folder.

- Explorer that "test-output" folder. then we can see the "index.html" file.

- Right click on "index.html" file then select open with -> Web browser - To see the HTML report in Eclipse.


(Also the testng-customsuite.xml file will create automatically and configure the web driver test. Path = C:\Users\arunraj\AppData\Local\Temp\testng-eclipse--360075510\testng-customsuite.xml)

Steps for Downloading And Installing Testng In Eclipse For WebDriver



-> TestNG is very powerful and easy to use framework and it is supported by tools like Eclipse, Maven, IDEA, etc..

-> Here we are going to use TestNG Framework with Eclipse so obviously you must have installed latest Java development kit (JDK) in your system and you must have Eclipse.




TestNG Installation Steps In Eclipse


Refer this link -> http://www.softwaretestingmentor.com/selenium-tutorials/how-to-setup-testng-with-selenium-webdriver-in-eclipse-ide/


1) Open Eclipse and go to Menu Help -> Install New Software. It will open new software installation window.

2) In new software installation window, Type http://beust.com/eclipse exactly in Work with field and click on Add button.

For Eclipse 3.4 and above, enter http://beust.com/eclipse.
For Eclipse 3.3 and below, enter http://beust.com/eclipse1.

3) Type name as "TestNG" and select "ok"

4) TestNG should get displayed under the name section, select the TestNG check box, click next and finish installation. ( Note: If TestNG already installed, then Next button is disabled.).

5) Restart eclipse to finalize installation. After restarting eclipse TestNG will get configured automatically in eclipse IDE.






Error facing while install TestNG with eclipse.


We may face after step(3) - Type name as "TestNG" and select "ok".  like below


" Problem occurred

"installing Software" has encountered a problem.

An error occurred while collecting items to be installed "


So we need to restart Eclipse and then follow the steps in above TestNG Installation Steps In Eclipse.





How to verify TestNG installed successfully in Eclipse


-> Once you have installed the plug-in, restart Eclipse

-> select the menu Window -> Show View -> Other

-> Select Java category, then we can see the TestNG is listed.

-> And Click the Testng and observe the below scenario.

1) If TestNG tab will open in console without any error then TestNG installed Successfully.
2) If TestNG tab will open in console with any error then TestNG not installed Successfully.
3) If TestNG is not listed under Java category then the TestNG is not installed in our eclipse.

Similarities and Difference Between Junit and TestNG Framework For WebDriver




Similarities Between JUnit and TestNG


1) We can create test suite in JUnit and TestNG both frameworks.

2) Timeout Test Is possible very easily in both the frameworks.

3) We can ignore specific test case execution from suite in both the frameworks.

4) It is possible to create expected exception test in both the frameworks.

5) Annotations - Few annotations are similar in both frameworks suite like @Test, @BeforeClass, @AfterClass. JUnit's Annotations @Before and @After are similar to TestNG's @BeforeMethod and @AfterMethod annotations.




Difference Between JUnit and TestNG


1) In TestNG, Parameterized test configuration is very easy while It is very hard to configure Parameterized test in JUnit.

2) TestNG support group test but it is not supported in JUnit.

3) TestNG has a feature to configure dependency test. Dependency test configuration is not possible in JUnit.

4) TestNG support @BeforeTest, @AfterTest, @BeforeSuite, @AfterSuite, @BeforeGroups, @AfterGroups which are not supported in JUnit.

5) Test prioritization, Parallel testing is possible in TestNG. It is not supported by JUnit.

Introduction Of TestNG




-> TestNG is unit testing framework. and its most popular among all java developers and selenium webdriver automation test engineers.

-> TestNG's development is inspired from combination of NUnit and JUnit. Its have all features from JUnit and also its have more features comapare to JUnit.



TestNG Annotations

-> The main reason behind TestNG's popularity is we can create and configure test case and test suite very easily using many different annotations of TestNG.

-> Few annotations are similiar with JUnit. Also its have more annotations.

-> Annotations in TestNG are which guides you what to do next or which method should be exeute next.

-> TestNG has also facility to pass parameters with annotations.


1) @Test
2) @BeforeMethod
3) @AfterMethod
4) @BeforeClass
5) @AfterClass
6) @BeforeTest
7) @AfterTest
8) @BeforeSuite
9) @AfterSuite
10) @DataProvider
11) @BeforeGroups
12) @AfterGroups
13) @Parameters
14) @Factory
15) @Listeners



1) @Test

-> Generally method under @Test used to write all testing related activity.
-> We can have any number of @Test method in single class of our test.



2) @BeforeMethod

-> Any Method which its marked as BeforeMethod will execute before each and every @Test Method Annotations.
-> Generally method under @BeforeMethod used to initializing browser or environment related setup.
-> The method under @BeforeMethod annotation will executed before each @Test annotations. That means if we have four @Test annotaions in your class, then the @BeforeMethod will execute four times.
-> Its same as @Before annoation in JUnit.



3) @AfterMethod

-> Any Method which its marked as BeforeMethod will execute after each and every @Test Method Annotations.
-> Generally method under @BeforeMethod used to close the instances.
-> The method under @AfterMethod annotation will executed after each @Test annotations. That means if we have four @Test annotaions in your class, then the @AfterMethod will execute four times.
-> Its same as @After annoation in JUnit.



4) @BeforeClass

-> Methods under @BeforeClass will execute before any one of the first test method starts execution.
-> It will execute only once even if there are multiple @Test method in our class.



5) @AfterClass

-> The method under @AfterClass will execute all the completion of @Test methods exection in class.
-> It will execute only once even if there are multiple @Test method in our class.



6) @BeforeTest

-> @BeforeTest annotated method will be executed before the any @Test annotated method of those classes which are inside <test> tag in testng.xml file.



7) @AfterTest

-> @AfterTest annotated method will be executed when all @Test annotated methods completes its execution of those classes which are inside <test> tag in testng.xml file.



8) @BeforeSuite

-> Method marked with @BeforeSuite annotation will run before the all suites from test.



9) @AfterSuite

-> @AfterSuite annotated method will start running when execution of all tests executed from current test suite.



10) @DataProvider

When you use @DataProvider annotation for any method that means you are using that method as a data supplier. Configuration of @DataProvider annotated method must be like it always return Object[][] which we can use in @Test annotated method.
VIEW PRACTICAL EXAMPLE OF @DataProvider ANNOTATION


11) @BeforeGroups

@BeforeGroups annotated method will run before the first test run of that specific group.


12) @AfterGroups

@AfterGroups annotated method will run after all test methods of that group completes its execution.


13) @Parameters

When you wants to pass parameters in your test methods, you need to use @Parameters annotation.
VIEW PRACTICAL EXAMPLE OF @Parameters ANNOTATION


14) @Factory

When you wants to execute specific group of test cases with different values, you need to use @Factory annotation. An array of class objects is returned by @Factory annotated method and those TestNG will those objects as test classes.

 
15) @Listeners

@Listeners are used to with test class. It is helpful for logging purpose.



Major Features


1) TestNG has a built in multiple Before and After and other annotations like @BeforeSuite, @AfterSuite, @BeforeTest, @BeforeGroups, @DataProvider, @Parameters, @Test etc.. All the TestNG annotations are very easy to understand and implement.

2) we can configure dependent test method. That means Test1() is dependent to Test2(). or else if test we cn configure if test1() is fail means Test1() has to be execute or not.

3) There is not required to extend any class in TestNG

4) We can configure our test suite using test methods, classes, packages, groups, etc.. in single testng.xml file.

5) Support of configuring test groups like backendtest-group, frontendtest-group etc..

6) we can also tell TestNG to execute only specific group/groups.

7) TestNG is supported by many tools and plug-ins like Eclipse, Maven, IDEA, etc..

8) TestNG has built in HTML report and XML report generation facility. It has also built in  logging facility.

9) Support for data-driven testing (with @DataProvider).

10) Flexible test configuration.

11) Ability to re-execute failed test cases.

12) TestNG also supports
-> parallel testing
-> Parameterization (Passing parameters values through XML configuration)
-> Data Driven Testing(executing same test method multiple times using different data)



How to use For Each loop in Java



-> It was introduced in JDK 1.5

-> Its mainly used to traverse the elements from array or collections.

-> The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.


Syntex:

for(data_type variable : array | collection)
{

}


Example :

class ForEachExample1{ 
  public static void main(String args[]){ 
   int arr[]={12,13,14,44}; 
 
   for(int i:arr){ 
     System.out.println(i); 
   } 
 
 }  

     

Output:12
       13
       14
       44