Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TestNG - priority of @AfterMethod

Tags:

java

testng

Is it possible to call @AfterMethod methods in specific order? I have an example code:

public class PriorityTest {

@BeforeClass(alwaysRun = true)
public void setUp() throws Exception {
    System.out.println("BeforeClass PriorityTest.java");
}

@Test
public void defaultPriority(){
    System.out.println("default");
}
@Test (priority = 3)
public void t1(){
    System.out.println("t1");
}
@Test (priority = 2)
public void t2(){
    System.out.println("t2");
}
@Test (priority = 1)
public void t3(){
    System.out.println("t3");
}
@Test (priority = -1)
public void t_1(){
    System.out.println("t -1");
}

@AfterMethod
public void after2(){
    System.out.println("after2");
}
@AfterMethod
public void after1(){
    System.out.println("after1");
}

}

Priority of @Test works perfectly. I want to do the same with @AfterMethod, but when I write code @AfterMethod (priority = 1) it is compilation error. When I run without priority there is always alphabetically order (only method name matters). Here is the output: BeforeClass PriorityTest.java t -1 after1 after2 default after1 after2 t3 after1 after2 t2 after1 after2 t1 after1 after2

Is there any possibility to call that methods in specific order (e.g. special paremeter or annotation)?

PS. I know I can write one AfterMethod and then call methods in specific order, but I think about many AfterMethod annotations.

like image 817
kotoj Avatar asked Apr 19 '16 08:04

kotoj


1 Answers

@AfterMethod doesn't support priority parameter. But it has dependsOnMethods and dependsOnGroups that can be used instead.

dependsOnMethods

The list of methods this method depends on. There is no guarantee on the order on which the methods depended upon will be run, but you are guaranteed that all these methods will be run before the test method that contains this annotation is run. Furthermore, if any of these methods was not a SUCCESS, this test method will not be run and will be flagged as a SKIP. If some of these methods have been overloaded, all the overloaded versions will be run.

dependsOnGroups

The list of groups this method depends on. Every method member of one of these groups is guaranteed to have been invoked before this method. Furthermore, if any of these methods was not a SUCCESS, this test method will not be run and will be flagged as a SKIP.

In your case dependsOnMethods can be used.

@AfterMethod
public void after2(){
    System.out.println("after2");
}
@AfterMethod(dependsOnMethods = "after2")
public void after1(){
    System.out.println("after1");
}
like image 198
Evgeny Avatar answered Sep 21 '22 08:09

Evgeny