Prioritizing / Sequencing of Test Cases in TestNG:
- When you want to put a number of tests under a test class and want to run everyone in one shot, then such situations will happen.
- With the help of TestNG ‘@Test‘ annotation, we can do many tests in a single Testing file.
- The number of test in the same test class and all to run in one shot.
- You can run one or more test cases in your TestNG.xml file.
- If we do not give @Test priority then execute @Test in alphabetical order.
Syntax:
1 | @Test(priority = 1) |
1. Without / Zero Priority:
- By default all the priorities for the tests will be zero (ie, if you do not set a preference, it will give priority as zero).
- If you give priority to all test cases, then according to all the tests it will be executed in alphabetical order.
Scenario’s:
- Create three methods (a,b,c).
- Without giving priority to any method execute script.
Example: Example Test case without / Zero priority.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import org.testng.annotations.Test; public class Annotations_Sequence { public class WithOutPriority { @Test public void c() { System.out.println("In C method"); } @Test public void b() { System.out.println("In B method"); } @Test public void a() { System.out.println("In A method"); } } } |
Output:
1 2 3 4 5 | In A method In B method In C method |
Note: It has not been executed in the sequence mentioned in the class. By default, the methods annotated by @Test are executed alphabetically.
2. With Priority:
- All test cases will be executed on priority basis.
Syntax:
1 | @Test(priority = 1) |
Scenario’s:
- Create three methods (a,b,c).
- Give priority to each method then execute script.
Example: Execute Test case to Prioritizing / Sequencing of Test Cases in TestNG.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import org.testng.annotations.Test; public class Priority { public class WithOutPriority { @Test(priority = 1) public void c() { System.out.println("In C method"); } @Test(priority = 2) public void b() { System.out.println("In B method"); } @Test(priority = 3) public void a() { System.out.println("In A method"); } } } |
Output:
1 2 3 4 5 | In C method In B method In A method |
Note: priority = 1 will execute the test first and priority = 2 will execute second and priority = 3 will execute the final. In this way, we can prioritize tests in testNG to control the execution flow.