Showing posts with label TestNG. Show all posts
Showing posts with label TestNG. Show all posts

Thursday, June 19, 2014

TestNG Configuration in maven

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>SeleniumMavenTestNGSuccessCase</groupId>
  <artifactId>SeleniumMavenTestNGSuccessCase</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>SeleniumMavenTestNGSuccessCase</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
 
  <dependencies>
   <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>6.3.1</version>
      <scope>test</scope>
    </dependency>
 </dependencies>
 <build>
 <plugins>
 
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.16</version>
        <configuration>
     
           <suiteXmlFiles>
                        <suiteXmlFile>src/main/resources/Second/testng.xml</suiteXmlFile>
                        <suiteXmlFile>src/main/resources/Second/testng-2.xml</suiteXmlFile>
                       
                    </suiteXmlFiles>
           </configuration>
         
     
      </plugin>

</plugins>
 </build>
</project>

Thursday, June 12, 2014

Threading Test

package ThreadingTest;

import org.testng.annotations.Test;

public class TestNGAnnotationTestMethodTimeOutExample {
@Test(timeOut = 2000)
public void timeOutTestMethodOne() throws InterruptedException {
Thread.sleep(5000);
System.out.println("TimeOut Test Method One!!");
}

@Test(timeOut = 5000)
public void timeOutTestMethodTwo() throws InterruptedException {
Thread.sleep(3000);
System.out.println("TimeOut Test Method Two!!");
}

@Test(timeOut = 2000)
public void timeOutTestMethodRunForEver() {
while (true) {
// Do nothing
}
}
}



package ThreadingTest;

import org.testng.annotations.*;

public class TestNGTimeTest {

@Test(timeOut = 1000, invocationCount = 100, successPercentage = 98)
public void testInvocationCount() throws Exception {
Thread.sleep(100);
System.out.println("waitForAnswer");
}
}


package ThreadingTest;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.testng.annotations.Test;

public class ThreadExecutorServiceDemo {
private static final String ERROR_MSG = "From thread you asked me throw an exception";

@Test
public void testUsingExecutorService() throws InterruptedException,
ExecutionException {
MyCallableService service = new MyCallableService(false);
Future<String> returnValue = Executors
.newSingleThreadScheduledExecutor().submit(service);
System.out.println(returnValue.get());
}

@Test(expectedExceptions = ExecutionException.class, expectedExceptionsMessageRegExp = ".*"
+ ERROR_MSG + ".*")
public void testUsingExecutorServiceWithException()
throws InterruptedException, ExecutionException {
MyCallableService anotherService = new MyCallableService(true);
Future<String> anotherReturnValue = Executors
.newSingleThreadScheduledExecutor().submit(anotherService);
System.out.println(anotherReturnValue.get());
}

@Test
public void testUsingThreads() throws InterruptedException {
MyThreadService mt = new MyThreadService(false);
mt.start();
while (mt.isAlive() == true) {
Thread.sleep(10000);
}
System.out.println(mt.getServiceName());
}

@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = ERROR_MSG)
public void testUsingThreadsWithExceptions() throws InterruptedException {
MyThreadService mt = new MyThreadService(true);
mt.start();
while (mt.isAlive() == true) {
Thread.sleep(10000);
}
System.out.println(mt.getServiceName());
}

public class MyThreadService extends Thread {
private boolean throwException;
private String serviceName;

public String getServiceName() {
return serviceName;
}

public MyThreadService(boolean throwException) {
this.throwException = throwException;
}

public void run() {
try {
sleep(25000);
this.serviceName = "TestNG threaded Service";
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (throwException) {
throw new RuntimeException(ERROR_MSG);
}
}
}

public class MyCallableService implements Callable<String> {
private boolean throwException;

public MyCallableService(boolean throwException) {
this.throwException = throwException;
}

@Override
public String call() throws Exception {
Thread.sleep(25000);
if (throwException) {
throw new RuntimeException(ERROR_MSG);
}
return "Callable Service Invoked";
}
}
}


package ThreadingTest;

import org.testng.annotations.Test;

public class ThreadProgram1 {

@Test(threadPoolSize = 3, invocationCount = 20)
public void concurrencyTest() {
System.out.print(" " + Thread.currentThread().getId());
}

}


package ThreadingTest;

import org.testng.annotations.Test;

public class ThreadUnsafe {
private static int[] accounts = new int[] { 0, 0 };
private static int MAX = 1000;

@Test(threadPoolSize = 1000, invocationCount = 1000, timeOut = 2000)
public void swap() {
int amount = (int) (MAX * Math.random());
accounts[1] += amount;
accounts[0] -= amount;
System.out.println("Account[0]: " + accounts[0]);
System.out.println("Account[1]: " + accounts[1]);
int balance = checkBalance();
assert (balance == 0);
}

public int checkBalance() {
int sum = 0;
for (int i = 0; i < accounts.length; i++) {
sum += accounts[i];
}
System.out.println("Balance : " + sum);
return sum;
}

public static void main(String[] args) {
ThreadUnsafe tu = new ThreadUnsafe();
tu.swap();
}
}

Threading Priority test

package ThreadingTest.Priority;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value={ElementType.METHOD, ElementType.TYPE})
public @interface Priority {
  int value() default 0;
}


package ThreadingTest.Priority;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import org.testng.IMethodInstance;
import org.testng.IMethodInterceptor;
import org.testng.ITestContext;


public class PriorityInterceptor implements IMethodInterceptor {

      public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
        Comparator<IMethodInstance> comparator = new Comparator<IMethodInstance>() {
       
          private int getPriority(IMethodInstance mi) {
            int result = 0;
            Method method = mi.getMethod().getMethod();
            Priority a1 = method.getAnnotation(Priority.class);
            if (a1 != null) {
              result = a1.value();
            } else {
              Class cls = method.getDeclaringClass();
              Priority classPriority = (Priority) cls.getAnnotation(Priority.class);
              if (classPriority != null) {
                result = classPriority.value();
              }
            }
            return result;
          }

          public int compare(IMethodInstance m1, IMethodInstance m2) {
            return getPriority(m1) - getPriority(m2);
          }
       
        };
        IMethodInstance[] array = methods.toArray(new IMethodInstance[methods.size()]);
        Arrays.sort(array, comparator);

        return Arrays.asList(array);
      }

    }

package ThreadingTest.Priority;

import org.testng.annotations.Test;

public class PriorityTestPlan   {
  @Test
  public void method1() { System.out.println("M1 Default priority");}

  @Priority(1)
  @Test
  public void method2()  { System.out.println("M2 Priority 1");}
  
  @Priority(3)
  @Test
  public void method3()  { System.out.println("M3 Priority 3");}
  
  @Priority(-1)
  @Test
  public void method4()  { System.out.println("M4 Priority -1");}

  @Priority(2)
  @Test
  public void method5()  { System.out.println("M5 Priority 2");}

  @Priority(2)
  @Test
  public void method6()  { System.out.println("M6 Priority 2");}

}


<suite name="PriorityTestSuite" verbose="1" >
    <listeners>
        <listener class-name="ThreadingTest.Priority.PriorityInterceptor" />
    </listeners>
    
    <test name="PriorityTestPlan" preserve-order="true">
    <classes>
        <class name="ThreadingTest.Priority.PriorityTestPlan"></class>
    </classes>
    </test>
</suite> 

TestSuite

package TestSuite;

import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;

//show the use of @BeforeSuite and @BeforeTest
public class TestConfig {

@BeforeSuite
public void testBeforeSuite() {
System.out.println("testBeforeSuite()");
}

@AfterSuite
public void testAfterSuite() {
System.out.println("testAfterSuite()");
}

@BeforeTest
public void testBeforeTest() {
System.out.println("testBeforeTest()");
}

@AfterTest
public void testAfterTest() {
System.out.println("testAfterTest()");
}

}


package TestSuite;

import org.testng.annotations.Test;

public class TestDatabase {

@Test(groups = "db")
public void testConnectOracle() {
System.out.println("testConnectOracle()");
}

@Test(groups = "db")
public void testConnectMsSQL() {
System.out.println("testConnectMsSQL");
}

@Test(groups = "db-nosql")
public void testConnectMongoDB() {
System.out.println("testConnectMongoDB");
}

@Test(groups = { "db", "brokenTests" })
public void testConnectMySQL() {
System.out.println("testConnectMySQL");
}

}


package TestSuite;

import org.testng.annotations.Test;

public class TestOrder {

@Test(groups={"orderBo", "save"})
public void testMakeOrder() {
 System.out.println("testMakeOrder");
}

@Test(groups={"orderBo", "save"})
public void testMakeEmptyOrder() {
 System.out.println("testMakeEmptyOrder");
}

@Test(groups="orderBo")
public void testUpdateOrder() {
System.out.println("testUpdateOrder");
}

@Test(groups="orderBo")
public void testFindOrder() {
System.out.println("testFindOrder");
}

}


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestAll">

<test name="order">
<classes>
<class name="TestSuite.TestConfig" />
<class name="TestSuite.TestOrder" />
</classes>
</test>

<test name="database">
<classes>
<class name="TestSuite.TestConfig" />
<class name="TestSuite.TestDatabase" />
</classes>
</test>

</suite>

Test All Of Particaular Package

package TestAllOfParticaularPackage;

import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;

//show the use of @BeforeSuite and @BeforeTest
public class TestConfig {

@BeforeSuite
public void testBeforeSuite() {
System.out.println("testBeforeSuite()");
}

@AfterSuite
public void testAfterSuite() {
System.out.println("testAfterSuite()");
}

@BeforeTest
public void testBeforeTest() {
System.out.println("testBeforeTest()");
}

@AfterTest
public void testAfterTest() {
System.out.println("testAfterTest()");
}

}


package TestAllOfParticaularPackage;

import org.testng.annotations.Test;

public class TestDatabase {

@Test(groups = "db")
public void testConnectOracle() {
System.out.println("testConnectOracle()");
}

@Test(groups = "db")
public void testConnectMsSQL() {
System.out.println("testConnectMsSQL");
}

@Test(groups = "db-nosql")
public void testConnectMongoDB() {
System.out.println("testConnectMongoDB");
}

@Test(groups = { "db", "brokenTests" })
public void testConnectMySQL() {
System.out.println("testConnectMySQL");
}

}


package TestAllOfParticaularPackage;

import org.testng.annotations.Test;

public class TestOrder {

@Test(groups={"orderBo", "save"})
public void testMakeOrder() {
 System.out.println("testMakeOrder");
}

@Test(groups={"orderBo", "save"})
public void testMakeEmptyOrder() {
 System.out.println("testMakeEmptyOrder");
}

@Test(groups="orderBo")
public void testUpdateOrder() {
System.out.println("testUpdateOrder");
}

@Test(groups="orderBo")
public void testFindOrder() {
System.out.println("testFindOrder");
}

}


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestAll">

<test name="order">
<packages>
<package name="TestAllOfParticaularPackage.*" />
</packages>
</test>

</suite>

Include Or ExcludeTestSuite test

package IncludeOrExcludeTestSuite;

import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;

//show the use of @BeforeSuite and @BeforeTest
public class TestConfig {

@BeforeSuite
public void testBeforeSuite() {
System.out.println("testBeforeSuite()");
}

@AfterSuite
public void testAfterSuite() {
System.out.println("testAfterSuite()");
}

@BeforeTest
public void testBeforeTest() {
System.out.println("testBeforeTest()");
}

@AfterTest
public void testAfterTest() {
System.out.println("testAfterTest()");
}

}


package IncludeOrExcludeTestSuite;

import org.testng.annotations.Test;

public class TestDatabase {

@Test(groups = "db")
public void testConnectOracle() {
System.out.println("testConnectOracle()");
}

@Test(groups = "db")
public void testConnectMsSQL() {
System.out.println("testConnectMsSQL");
}

@Test(groups = "db-nosql")
public void testConnectMongoDB() {
System.out.println("testConnectMongoDB");
}

@Test(groups = { "db", "brokenTests" })
public void testConnectMySQL() {
System.out.println("testConnectMySQL");
}

}

package IncludeOrExcludeTestSuite;

import org.testng.annotations.Test;

public class TestOrder {

@Test(groups={"orderBo", "save"})
public void testMakeOrder() {
 System.out.println("testMakeOrder");
}

@Test(groups={"orderBo", "save"})
public void testMakeEmptyOrder() {
 System.out.println("testMakeEmptyOrder");
}

@Test(groups="orderBo")
public void testUpdateOrder() {
System.out.println("testUpdateOrder");
}

@Test(groups="orderBo")
public void testFindOrder() {
System.out.println("testFindOrder");
}

}


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestAll">

  <test name="order">
<classes>
<class name="IncludeOrExcludeTestSuite.TestConfig" />
<class name="IncludeOrExcludeTestSuite.TestOrder">
<methods>
<include name="testMakeOrder" />
<include name="testUpdateOrder" />

<exclude name="testMakeOrder" />

</methods>
</class>
</classes>
  </test>

</suite>

Groups Priority test Depends On Methods

package GroupsPriorityDependsOnMethods;

import org.testng.annotations.Test;

public class Grp {
 @Test(groups={"smoke"},priority=4)
 public void a()
 {
 System.out.println("a method");
 }
 @Test(groups={"smoke"},priority=5)
 public void b()
 {
  System.out.println("b method");
 }
 @Test(groups={"regression"},priority=2)
 public void c()
 {
  System.out.println("c method");
 }
 @Test(groups={"smoke","sanity"},priority=3)
 public void d()
 {
  System.out.println("d method");
 }
 @Test(groups={"smoke"},priority=1,dependsOnMethods={"b","d"})
 public void e()
 {
  System.out.println("e method");
 }



}


package GroupsPriorityDependsOnMethods;

import org.testng.annotations.Test;

public class Grp1 {
 @Test(groups={"sanity"})
 public void a1()
 {
 System.out.println("a1 method");
 }
 @Test(groups={"smoke","sanity"})
 public void b1()
 {
  System.out.println("b1 method");
 }
 @Test(groups={"regression,smoke"})
 public void c1()
 {
  System.out.println("c1 method");
 }
 @Test(groups={"smoke"})
 public void d1()
 {
  System.out.println("d1 method");
 }
 @Test(groups={"sanity"})
 public void e1()
 {
  System.out.println("e1 method");
 }



}

package GroupsPriorityDependsOnMethods;

import org.testng.annotations.Test;

public class Grp2 {
 @Test(groups={"sanity"})
 public void a2()
 {
 System.out.println("a2 method"); 
 }
 @Test(groups={"regression"})
 public void b2()
 {
  System.out.println("b2 method"); 
 }
 @Test(groups={"smoke"})
 public void c2()
 {
  System.out.println("c2 method");
 }
 @Test(groups={"regerssion"})
 public void d2()
 {
  System.out.println("d2 method");
 }
 @Test(groups={"sanity","smoke"})
 
 public void e2()
 {
  System.out.println("e2 method");
 }
 
 

}


<suite name="Suite1" verbose="1" >
  <test name="build1" >
  <classes>  
  <class name="GroupsPriorityDependsOnMethods.Grp" />
    <class name="GroupsPriorityDependsOnMethods.Grp1" />
      <class name="GroupsPriorityDependsOnMethods.Grp2" />  
  </classes>
  <groups>
<run>
  <include name="sanity"/>
  <include name="smoke"/>
  <exclude name="regression" />
  </run> 
  </groups> 
  </test>
  </suite>

Groupstest On Class And Method

package GroupsOnClassAndMethod;

import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;

public class TestGroup {

@BeforeGroups("database")
public void setupDB() {
System.out.println("setupDB()");
}

@AfterGroups("database")
public void cleanDB() {
System.out.println("cleanDB()");
}

@Test(groups= "selenium-test")
public void runSelenium() {
System.out.println("runSelenium()");
}

@Test(groups= "selenium-test")
public void runSelenium1() {
System.out.println("runSelenium()1");
}

@Test(groups = "database")
public void testConnectOracle() {
System.out.println("testConnectOracle()");
}

@Test(groups = "database")
public void testConnectMsSQL() {
System.out.println("testConnectMsSQL");
}

@Test(dependsOnGroups = {"database","selenium-test"})
public void runFinal() {
System.out.println("runFinal");
}

}


package GroupsOnClassAndMethod;

import org.testng.annotations.Test;

@Test(groups= "selenium-test")
public class TestSelenium {

public void runSelenium() {
System.out.println("runSelenium()");
}

public void runSelenium1() {
System.out.println("runSelenium()1");
}

}


<suite name="TestAll">

<test name="final">
<classes>
<class name="GroupsOnClassAndMethod.TestSelenium" />
<class name="GroupsOnClassAndMethod.TestGroup" />
</classes>
</test>

<!-- Run test method on group "selenium" only -->
<test name="selenium">

<groups>
<run>
<include name="selenium-test" />
</run>
</groups>

<classes>
<class name="GroupsOnClassAndMethod.TestSelenium" />
<class name="GroupsOnClassAndMethod.TestGroup" />
</classes>

</test>

</suite>

GroupIncludeOrExclude test

package GroupIncludeOrExclude;

import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;

//show the use of @BeforeSuite and @BeforeTest
public class TestConfig {

@BeforeSuite
public void testBeforeSuite() {
System.out.println("testBeforeSuite()");
}

@AfterSuite
public void testAfterSuite() {
System.out.println("testAfterSuite()");
}

@BeforeTest
public void testBeforeTest() {
System.out.println("testBeforeTest()");
}

@AfterTest
public void testAfterTest() {
System.out.println("testAfterTest()");
}

}


package GroupIncludeOrExclude;

import org.testng.annotations.Test;

public class TestDatabase {

@Test(groups = "db")
public void testConnectOracle() {
System.out.println("testConnectOracle()");
}

@Test(groups = "db")
public void testConnectMsSQL() {
System.out.println("testConnectMsSQL");
}

@Test(groups = "db-nosql")
public void testConnectMongoDB() {
System.out.println("testConnectMongoDB");
}

@Test(groups = { "db", "brokenTests" })
public void testConnectMySQL() {
System.out.println("testConnectMySQL");
}

}


package GroupIncludeOrExclude;

import org.testng.annotations.Test;

public class TestOrder {

@Test(groups={"orderBo", "save"})
public void testMakeOrder() {
 System.out.println("testMakeOrder");
}

@Test(groups={"orderBo", "save"})
public void testMakeEmptyOrder() {
 System.out.println("testMakeEmptyOrder");
}

@Test(groups="orderBo")
public void testUpdateOrder() {
System.out.println("testUpdateOrder");
}

@Test(groups="orderBo")
public void testFindOrder() {
System.out.println("testFindOrder");
}

}


<suite name="TestAll">

  <test name="database">
<groups>
<run>
<exclude name="brokenTests" />
<include name="db" />
</run>
</groups>

<classes>
<class name="GroupIncludeOrExclude.TestDatabase" />
<class name="GroupIncludeOrExclude.TestConfig" />

</classes>
  </test>

</suite>

GroupDependencyTest

package GroupDependencyTest;

import org.testng.annotations.Test;

public class TestApp {

//Run if all methods from "deploy" and "db" groups are passed.
@Test(dependsOnGroups={"deploy","db"})
public void method1() {
System.out.println("This is method 1");
//throw new RuntimeException();
}

//Run if method1() is passed.
@Test(dependsOnMethods = { "method1" })
public void method2() {
System.out.println("This is method 2");
}

}


package GroupDependencyTest;

import org.testng.annotations.Test;

public class TestDatabase {

//belong to "db" group,
//Run if all methods from "deploy" group are passed.
@Test(groups="db", dependsOnGroups="deploy")
public void initDB() {
System.out.println("This is initDB()");
}

//belong to "db" group,
//Run if "initDB" method is passed.
@Test(dependsOnMethods = { "initDB" }, groups="db")
public void testConnection() {
System.out.println("This is testConnection()");
}

}

package GroupDependencyTest;

import org.testng.annotations.Test;

//all methods of this class are belong to "deploy" group.
//Run the tests on the order specified in group
@Test(groups="deploy")
public class TestServer {

@Test
public void deployServer() {
System.out.println("Deploying Server...");
}

//Run this if deployServer() is passed.
@Test(dependsOnMethods="deployServer")
public void deployBackUpServer() {
System.out.println("Deploying Backup Server...");
}

}
testng.xml

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestDependency">

  <test name="TestCase1">

<classes>
 <class
name="GroupDependencyTest.TestApp">
 </class>
 <class
name="GroupDependencyTest.TestDatabase">
 </class>
 <class
name="GroupDependencyTest.TestServer">
 </class>
</classes>

  </test>

</suite>

Factory Annotation

package FactoryAnnotation;

import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.Factory;

public class DynamicTestPlanTest {
    TestPlan1 obj1;
    TestPlan2 obj2;
   
    @Factory
    public Object[] setUp() throws Exception {
       List list=new ArrayList();
       
        int a=30,b=20;
       
        if(a>b){
            obj1=new TestPlan1();
            list.add(obj1);
        }else{
            obj2=new TestPlan2();
            list.add(obj2);
        }
       
        Object[] data = list.toArray();
        return data;
    }
   
}

package FactoryAnnotation;

import org.testng.annotations.Test;

public class TestPlan1{
    
    @Test
    public void testPlan1Method1()throws Exception {
        System.out.println("testPlan1Method1- invoked");
    }
    
    @Test
    public void testPlan1Method2()throws Exception {
        System.out.println("testPlan1Method2 - invoked");
    }
   

   @Test
    public void testPlan1Method3()throws Exception {
        System.out.println("testPlan1Method3- invoked");
    }
    
    @Test
    public void testPlan1Method4()throws Exception {
        System.out.println("testPlan1Method4 - invoked");
    } 
 }


package FactoryAnnotation;

import org.testng.annotations.Test;

public class TestPlan2{
    
  @Test
    public void testPlan2Method1()throws Exception {
        System.out.println("testPlan2Method1- invoked");
    }
    
    @Test
    public void testPlan2Method2()throws Exception {
        System.out.println("testPlan2Method2 - invoked");
    }

}

testng.xml

<suite name="DynamicTestPlanTestSuite" verbose="1" >
       
    <test name="DynamicTestPlanTest" preserve-order="true">
    <classes>
        <class name="FactoryAnnotation.DynamicTestPlanTest"></class>
    </classes>
    </test>
</suite> 

Dependency Test

package DependencyTest;

import org.testng.annotations.Test;

public class AppFailed {

//This test will be failed.
@Test
public void method1() {
System.out.println("This is method 1");
throw new RuntimeException();
}

@Test(dependsOnMethods = { "method1" })
public void method2() {
System.out.println("This is method 2");
}

}

testng.xml

<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="test-parameter">

    <test name="example1">

<parameter name="dbconfig" value="db.properties" />
<parameter name="poolsize" value="10" />

<classes>
 <class name="DataProvider.Xml.TestParameterXML" />
</classes>

    </test>

</suite>

Data Provider Using xml

package DataProvider.Xml;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class TestParameterXML {

Connection con;

@Test
@Parameters({ "dbconfig", "poolsize" })
public void createConnection(String dbconfig, int poolsize) {

System.out.println("dbconfig : " + dbconfig);
System.out.println("poolsize : " + poolsize);

Properties prop = new Properties();
InputStream input = null;

try {
 //get properties file from project classpath
 input = getClass().getClassLoader().getResourceAsStream(dbconfig);

 prop.load(input);

 String drivers = prop.getProperty("jdbc.driver");
 String connectionURL = prop.getProperty("jdbc.url");
 String username = prop.getProperty("jdbc.username");
 String password = prop.getProperty("jdbc.password");

 System.out.println("drivers : " + drivers);
 System.out.println("connectionURL : " + connectionURL);
 System.out.println("username : " + username);
 System.out.println("password : " + password);

 Class.forName(drivers);
 con = DriverManager.getConnection(connectionURL, username, password);

} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

}

testng.xml

<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="test-parameter">

    <test name="example1">

<parameter name="dbconfig" value="db.properties" />
<parameter name="poolsize" value="10" />

<classes>
 <class name="DataProvider.Xml.TestParameterXML" />
</classes>

    </test>

</suite>

Data Provider using annotation

package DataProvider.Annotation;

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;
}
}


package DataProvider.Annotation;

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

public class CharUtilsTest {
 // data provided through annotation
@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);

}
}

package DataProvider.Annotation;

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

public class TestParameterDataProvider {

@Test(dataProvider = "provideNumbers")
public void test(int number, int expected) {
Assert.assertEquals(number + 10, expected);
}

@DataProvider(name = "provideNumbers")
public Object[][] provideData() {

return new Object[][] {
{ 10, 20 },
{ 100, 110 },
{ 200, 210 }
};
}

}

package DataProvider.Annotation;

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

public class TestParameterDataProviderITestContext {
// in case of ITestContext it consult with xml file for which group to
// provide which data
@Test(dataProvider = "dataProvider", groups = { "groupA" })
public void test1(int number) {
System.out.println("I am executing groupA");
Assert.assertEquals(number, 1);
}

@Test(dataProvider = "dataProvider", groups = "groupB")
public void test2(int number) {
Assert.assertEquals(number, 2);
}

@DataProvider(name = "dataProvider")
public Object[][] provideData(ITestContext context) {

Object[][] result = null;

// get test name
// System.out.println(context.getName());

for (String group : context.getIncludedGroups()) {

System.out.println("group : " + group);

if ("groupA".equals(group)) {
result = new Object[][] { { 1 } };
break;
} else {
result = new Object[][] { { 2 } };
}

}
// /Group is not included .So,it gave null value .
if (result == null) {
result = new Object[][] { { 2 } };
}
return result;

}

}



package DataProvider.Annotation;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

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

public class TestParameterDataProviderMap {

@Test(dataProvider = "dbconfig")
public void testConnection(Map<String, String> map) {

for (Map.Entry<String, String> entry : map.entrySet()) {
 System.out.println("[Key] : " + entry.getKey()
                              + " [Value] : " + entry.getValue());
}

}

@DataProvider(name = "dbconfig")
public Object[][] provideDbConfig() {
Map<String, String> map = readDbConfig();
return new Object[][] { { map } };
}

public Map<String, String> readDbConfig() {

Properties prop = new Properties();
InputStream input = null;
Map<String, String> map = new HashMap<String, String>();

try {
 input = getClass().getClassLoader().getResourceAsStream("db.properties");

 prop.load(input);

 map.put("jdbc.driver", prop.getProperty("jdbc.driver"));
 map.put("jdbc.url", prop.getProperty("jdbc.url"));
 map.put("jdbc.username", prop.getProperty("jdbc.username"));
 map.put("jdbc.password", prop.getProperty("jdbc.password"));

} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return map;

}

}


package DataProvider.Annotation;

import java.lang.reflect.Method;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class TestParameterDataProviderMethod {

@Test(dataProvider = "dataProvider")
public void test1(int number, int expected) {
Assert.assertEquals(number, expected);
}

@Test(dataProvider = "dataProvider")
public void test2(String email, String expected) {
Assert.assertEquals(email, expected);
}

@DataProvider(name = "dataProvider")
public Object[][] provideData(Method method) {

Object[][] result = null;

if (method.getName().equals("test1")) {
result = new Object[][] {
{ 1, 1 }, { 200, 200 }
};
} else if (method.getName().equals("test2")) {
result = new Object[][] {
{ "test@gmail.com", "test@gmail.com" },
{ "test@yahoo.com", "test@yahoo.com" }
};
}

return result;

}

}

testng.xml

<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="test-parameter">

  <test name="example1">

<groups>
<run>
<include name="groupB" />
</run>
</groups>
 <!-- In this case DataProvider.Annotation.TestParameterDataProviderMap
 ,DataProvider.Annotation.TestParameterDataProviderMethod is not simultaneously executed only one is exceuted
  -->
<classes>
  <class
   name="DataProvider.Annotation.TestParameterDataProviderITestContext" />
    <class
   name="DataProvider.Annotation.TestParameterDataProviderMap" />
    <class
   name="DataProvider.Annotation.TestParameterDataProviderMethod" />
</classes>

  </test>

</suite>

Basic Usage

package BasicUsage;

import java.util.ArrayList;
import java.util.Collection;

import org.testng.AssertJUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

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");
    }

@BeforeMethod

public void setUp() {
        collection = new ArrayList();
        System.out.println("@Before - setUp");
    }

@AfterMethod
public void tearDown() {
        collection.clear();
        System.out.println("@After - tearDown");
    }

    @Test
    public void testEmptyCollection() {
        AssertJUnit.assertTrue(collection.isEmpty());
        System.out.println("@Test - testEmptyCollection");
    }

    @Test
    public void testOneItemCollection() {
        collection.add("itemA");
        AssertJUnit.assertEquals(1, collection.size());
        System.out.println("@Test - testOneItemCollection");
    }
}



package BasicUsage;

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

public class JunitTest2 {

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

}


package BasicUsage;

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



public class JunitTest3 {

@Test(enabled = false)
public void divisionWithException() {
 System.out.println("Method is not ready yet");
}

}

package BasicUsage;

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


public class JunitTest4 {

@Test(timeOut = 1000)
public void infinity() {
while (true);
}

}

package BasicUsage;

import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.testng.annotations.Test;

import com.beust.jcommander.Parameterized;

import java.util.Arrays;
import java.util.Collection;


// Paramterized test is done in differnt way in TestNG.So,program is showing error.
@Test
@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);
}

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


}