Hello Folks,

We have seen how a TestNG class executes methods when we do not provide any order to methods. You can refer those posts here:

Default Priority in a TestNG Class

Default Priority in an Inherited Class

But, you may require to execute methods in a certain order. Consider a scenario where you need to register a user and then same user needs to perform some actions. You write two test methods in a TestNG class say “RegisterUser” and “PerformSomeAction”. These methods must be run in order. First  “RegisterUser” followed by “PerformSomeAction” method. If we do not specify any order, TestNG will execute “PerformSomeAction” before “RegisterUser” and it will not serve your purpose. You must need to specify order explicitly. For this TestNG provides an attribute called “Priority”.

Priority:

  1. You need to write this element in small letters as “priority”.
  2. Priority is an element applicable only for @Test annotated methods.
  3. Priority should be an integer value.
  4. It can be negative , zero or positive number. If you write it is decimal, you must need to cast it into integer.
  5. TestNG will execute test methods from lowest to highest priority. Remember Lower priorities will be scheduled first.
  6. TestNG ignore default priority based on ASCII if priority value is provided.
  7. You can pass duplicate priority to test methods. In case of tie, TestNG will decide priority based on ASCII value.
  8. You can create a TestNG class with some test methods with priority and some without priority in same class.
  9. Test methods without priority will have default priority of Zero and execution sequence will be decided based on ASCII value.
  10. Suppose if you have three test methods with first two test methods say M1, M2 with priority as -1 and 2 respectively and third test methods say M3 without any priority. In this case, TestNG will have priority as M1=-1, M2=0 and M3=2. So FIrst M1 will be executed followed by M2 and M3.
  11. You can not define multiple priority element for a test method.
  12. You can not pass priority to methods through testng.xml.

Examples:

Scenario 1:  All test methods with priority. Apply Lower priorities will be scheduled first concept.

Output:
Negative Prioirty
Zeroth Priority
Positive Priority
Skipped Priority

Scenario 2: Mixed test methods with priority and without priority

Output:
M1withPriority
DispWithoutPriority
PrintWithoutPriority
M4withPriority

Scenario 3: A class with duplicate test priorities methods

Output:
M1withPriority
M4withPriority
DuplicatePriorityMethod1
DuplicatePriorityMethod2

More about TestNG in upcoming posts. Stay tuned.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappySelenium

 

2 thoughts on “TestNG Tutorials 22: @Test Annotation – Games Of Priority Of Methods In TestNG

Leave a Reply