Group by instances in testng

group-by-instances attribute is used to group tests by classes. Consider 2 classes with 2 methods in each class and each with priority as 1 , 2 respectively. So by default, methods will be executed in below sequence
  • class1method1
  • class2method1
  • class1method2
  • class2method2
If you have group-by-instances=”true”, methods will be executed in below sequence. Class1 methods will be executed first followed by class2 methods
  • class1method1
  • class1method2
  • class2method1
  • class2method2
Here is the source code of Class1.java
 
package org.softpost;

import org.testng.annotations.Test;

/**
 * Created by Sagar on 29-06-2016.
 */
public class Class1 {

    @Test(priority = 1)
    public void test1(){
        System.out.println("Test1 from Class1");
    }

    @Test(priority = 2)
    public void test2(){
        System.out.println("Test2 from Class1");
    }
}

Here is the Class2.java source code
 
package org.softpost;

import org.testng.annotations.Test;

/**
 * Created by Sagar on 29-06-2016.
 */
public class Class2 {

    @Test(priority = 1)
    public void test1(){
        System.out.println("Test1 from Class2");
    }

    @Test(priority = 2)
    public void test2(){
        System.out.println("Test2 from Class2");
    }

}

Here is the XML suite file.
 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Suite" parallel="classes" thread-count="5">
    <test name="Tests" group-by-instances="true">
        <classes>
            <class name="org.softpost.Class1" />
            <class name="org.softpost.Class2" />
        </classes>
    </test>
</suite>

Here is the output of above example.
 
[TestNG] Running:
C:UsersSagarIdeaProjectsTestNG-Projectsrc	est
esources	estng.xml
Test1 from Class1
Test2 from Class1
Test1 from Class2
Test2 from Class2

===============================================
Suite
Total tests run: 4, Failures: 0, Skips: 0
===============================================

group-by-instances also allows you to run the dependant tests of a single class instance in proper sequence.
 
<test verbose=”2″ name=”MytestCase” group-by-instances=”true” preserve-order=”true”>

Web development and Automation testing

solutions delivered!!