testng中的@AfterClass和@beforeclass执行两次

@AfterClass and @beforeclass in testng executing twice

你好我正在练习testng,我有一个简单的class如下:

public class testclass1 {
    @Test
    public void firstMethod() {
        System.out.println("first");
    }
    
    @Test
    public void secondMethod() {
        System.out.println("second");
    }
    @Test
    @BeforeSuite
    public void thirdMethod() {
        System.out.println("third- before suite");
    }
    @Test
    @AfterClass
    public void fourthMethod() {
        System.out.println("fourth- after class");
    }
    
}

执行时,结果为

[RemoteTestNG] detected TestNG version 7.3.0
third- before suite
first
fourth- after class
second
third- before suite
fourth- after class

我很困惑。为什么 before suite 和 after class 方法调用了两次?

只需删除 @AfterClass@BeforeSuite 中的 @Test 注释:

public class testclass1 {
    @Test
    public void firstMethod() {
        System.out.println("first");
    }
    
    @Test
    public void secondMethod() {
        System.out.println("second");
    }
    
    @BeforeSuite
    public void thirdMethod() {
        System.out.println("third- before suite");
    }
    
    @AfterClass
    public void fourthMethod() {
        System.out.println("fourth- after class");
    }
}

输出:

third- before suite
first
second
fourth- after class