Usually, a tester needs to execute the tests in a group as per requirement and in that group, tests are required to execute in a predefined order because of their dependency on each other.
TestNG gives us the facility to perform these actions with very easy to use annotation. Let's try to learn with an easy example-
Step 1 : Create a java test file with following code:
import org.testng.annotations.Test;
public class TestDummy1 extends TestBase{
@Test (groups = { "Sanity" })
public void Test1() throws Exception
{
System.out.println("Dummy Test 1 is called in Sanity group");
}
@Test (groups = { "Sanity" })
public void Test2() throws Exception
{
System.out.println("Dummy Test 2 is called in Sanity group");
}
@Test (groups = { "Regression" }, priority=2)
public void Test3() throws Exception
{
System.out.println("Dummy Test 3 is called in Regression group");
}
@Test (groups = { "Regression" }, priority=1)
public void Test4() throws Exception
{
System.out.println("Dummy Test 4 is called in Regression group");
}
@Test (groups = { "Regression" }, priority=3)
public void Test5() throws Exception
{
System.out.println("Dummy Test 5 is called in Regression group");
}
}
Step 2 : Create a testNG file with following code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<!-- <suite name="Suite" > -->
<suite name="Suite">
<listeners>
<listener class-name="com.listeners.TestNGListeners" />
</listeners>
<!--
<test name="DummyTest" parallel="tests">
<groups>
<run>
<include name="Sanity" />
</run>
</groups>
<classes>
<class name="com.tests.Dummy.TestDummy1" />
</classes>
</test> -->
<test name="DummyTest1" parallel="tests">
<groups>
<run>
<include name="Regression" />
</run>
</groups>
<classes>
<class name="com.tests.Dummy.TestDummy1" />
</classes>
</test>
</suite
Step 3: Execute the testNG file and you will get the result. Regression group will be executed as per the priority given in test methods.
Dummy Test 4 is called in Regression group
Dummy Test 3 is called in Regression group
Dummy Test 5 is called in Regression group
Step 4: Uncomment the other group(Sanity) of tests in testNG file and execute it again.
Dummy Test 1 is called in Sanity group
Dummy Test 2 is called in Sanity group