TestNG注解顺序

TestNG Annotations order

我对 TestNG 注释的操作顺序有疑问...我有以下代码:

public class AnnotationsTest {

    @BeforeSuite(alwaysRun = true)
    public static void beforeSuite() {
        System.out.println("@BeforeSuite");
    }

    @BeforeClass(alwaysRun = true)
    public static void beforeClass() {
        System.out.println("@BeforeClass");
    }

    @BeforeTest(alwaysRun = true)
    public static void beforeTest() {
        System.out.println("@BeforeTest");
    }

    @BeforeMethod(alwaysRun = true)
    public static void beforeMethod() {
        System.out.println("@BeforeMethod");
    }

    @AfterSuite(alwaysRun = true)
    public static void afterSuite() {
        System.out.println("@AfterSuite");
    }

    @AfterClass(alwaysRun = true)
    public static void afterClass() {
        System.out.println("@AfterClass");
    }

    @AfterTest(alwaysRun = true)
    public static void afterTest() {
        System.out.println("@AfterTest");
    }

    @AfterMethod(alwaysRun = true)
    public static void afterMethod() {
        System.out.println("@AfterMethod");
    }

    @Test
    public void test() {
        System.out.println("Test");
    }

    @Test
    public void test2() {
        System.out.println("Test2");
    }
}

我的输出如下:

我的问题是,为什么 @AfterTest 方法不是在每个 @Test 注释之后 运行? TestNG 是否将整个 class 视为 'Test'?似乎是这种情况,因为@BeforeTest 和@AfterTest 在@BeforeClass 和@AfterClass 之外,但我想确保我理解。我假设我可以在这种情况下使用@BeforeMethod 和@AfterMethod 在这个 class 中的 test1 和 test2 之前和之后执行。谢谢!

My question is, why is @AfterTest method not run after each @Test annotation?

Documentation所说

@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.

@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.

这里的主要混淆是@Test 注释和标记。假设您正在从 testng.xml 文件中执行上述代码。我们在该文件中编写 testng 文件标记序列的方式是 methods 。所以现在每个注释都有意义。即@Test 用于 class 中的方法。 @BeforeMethod 将在每个 @Test 注释之前执行。并且 @BeforeTest 注释在 testng.xml 文件中提到的 classes 之前执行,因为您可以看到标记包含标记。上述问题的简短答案是 @Test 用于 menthod @BeforeMethod 在每个 @Test 注释方法之前执行,@BeforeTest 在所有方法和标记中提到的 classes 之前执行。

@AfterMethod是在@Test方法之后执行的那个。同样,@BeforeMethod 是在每个 @Test 方法之前执行的。

您的输出显示方法的优先级 运行。