@BeforeClass方法不在每个类之前运行

我有两个类,每个类包含2个测试用例,根据我的说法,Test1类具有一个@Beforeclass的方法,该方法也应该在Test2类之前运行,但它不会运行。

    package WebPackage;

    import org.testng.annotations.Beforeclass;
    import org.testng.annotations.Test;

    public class Test1 {
        @Beforeclass
        public void test1() {

            System.out.println("printing Before Class Method");
        }
        @Test (priority = 1)
    public void test2() {

            System.out.println("printing test_2");
        }

        @Test (priority = 3)
    public void test3() {

            System.out.println("printing test_3");
        }
    }

Test2

    package WebPackage;

    import org.testng.annotations.Test;

    public class Test2 {

        @Test (priority = 1)
        public void test4() {

                System.out.println("printing test_4");
            }

            @Test (priority = 3)
        public void test5() {

                System.out.println("printing test_5");
            }
    }

Xml文件


    <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
    <suite name="Menu">
      <test name="WebPackage">
        <classes>
          <class name="WebPackage.Test1"/>
         <class name="WebPackage.Test2"/>
        </classes>
      </test> <!-- Test -->
    </suite> <!-- Suite -->

控制台

[RemoteTestNG] detected TestNG version 7.0.0
printing Before Class Method
printing test_2
printing test_3
printing test_4
printing test_5

===============================================
Menu
Total tests run: 4,Passes: 4,Failures: 0,Skips: 0
===============================================
lxg1201 回答:@BeforeClass方法不在每个类之前运行

BeforeClass仅在Test类启动时运行一次。因此。每个测试类仅执行一次。如果要对测试类中的每个测试方法都执行@Before,则使用它。

阅读参考-Difference between @Before,@BeforeClass,@BeforeEach and @BeforeAll

,

@BeforeClass将仅运行一次,然后再运行该类中带有@Test注释的任何方法。 Test2类中的任何方法都不会再次运行。

,

您可以使用BaseTest注释制作一个@BeforeClass类,然后每个Test类都使用BaseTest进行扩展。

BaseTest:

public class BaseTest {
    @BeforeClass
    public void test1() {
        System.out.println("printing Before Class Method");
    }
}

测试1:

public class Test1 extends BaseTest {
    @Test (priority = 1)
    public void test2() {
        System.out.println("printing test_2");
    }

    @Test(priority = 3)
    public void test3() {
        System.out.println("printing test_3");
    }
}

Test2:

public class Test2 extends BaseTest {
    @Test(priority = 1)
    public void test4() {
        System.out.println("printing test_4");
    }

    @Test (priority = 3)
    public void test5() {
        System.out.println("printing test_5");
    }
}

输出:

printing Before Class Method
printing test_2
printing test_3
printing Before Class Method
printing test_4
printing test_5
===============================================
Menu
Total tests run: 4,Passes: 4,Failures: 0,Skips: 0
===============================================
本文链接:https://www.f2er.com/3145880.html

大家都在问