如何在TestNG中指定方法名称顺序?


一个TestNG类可以包含各种TestNG方法,例如@BeforeTest, @AfterTest, @BeforeSuite, @BeforeClass, @BeforeMethod, @test等。在本文中,我们将解释不同TestNG方法的执行顺序。

TestNG包含以下方法来支持主要的@Test方法。执行顺序如下:

<beforeSuite> <beforeTest> <beforeClass> <beforeMethod> <test1> <afterMethod> <afterClass> <afterTest> <afterSuite>

此顺序中的关键点是

  • 首先,beforeSuite()方法只执行一次。

  • afterSuite()方法只执行一次。

  • 甚至beforeTest(), beforeClass(), afterClass()afterTest()方法也只执行一次。

  • beforeMethod()方法为每个测试用例(每次针对新的@Test)执行,但在执行测试用例之前。

  • afterMethod()方法为每个测试用例(每次针对新的@Test)执行,但在执行测试用例之后。

  • beforeMethod()afterMethod()之间,每个测试用例(@Test注解的方法)都会执行。

解决此问题的方法/算法

  • 步骤1 - 导入org.testng.annotations.* 用于TestNG。

  • 步骤2 - 写入注释为@test

  • 步骤3 - 为@test注解创建一个名为test1的方法。

  • 步骤4 - 重复test2test3的步骤。

  • 步骤5 - 编写不同的注解及其相应的方法。例如,@beforeSuite, @afterSuite, @beforeTest, @afterTest, @beforeClass, @afterClass, @beforeMethod, @afterMethod

  • 步骤6 - 现在创建如下所示的testng.xml

  • 步骤7 - 最后,运行testng.xml或直接在IDE中运行TestNG类,或者使用命令行编译并运行它。

示例

使用以下代码来显示不同TestNG方法的顺序:

import org.testng.annotations.*; import org.testng.annotations.Test; public class OrderofTestExecutionInTestNG { // test case 1 @Test public void testCase1() { System.out.println("in test case 1"); } // test case 2 @Test public void testCase2() { System.out.println("in test case 2"); } @BeforeMethod public void beforeMethod() { System.out.println("in beforeMethod"); } @AfterMethod public void afterMethod() { System.out.println("in afterMethod"); } @BeforeClass public void beforeClass() { System.out.println("in beforeClass"); } @AfterClass public void afterClass() { System.out.println("in afterClass"); } @BeforeTest public void beforeTest() { System.out.println("in beforeTest"); } @AfterTest public void afterTest() { System.out.println("in afterTest"); } @BeforeSuite public void beforeSuite() { System.out.println("in beforeSuite"); } @AfterSuite public void afterSuite() { System.out.println("in afterSuite"); } }

testng.xml

这是一个配置文件,用于组织和运行TestNG测试用例。当只需要执行有限的测试而不是完整的套件时,它非常方便。

<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name = "Suite1"> <test name = "test1"> <classes> <class name = "OrderofTestExecutionInTestNG"/> </classes> </test> </suite>

输出

in beforeSuite
in beforeTest
in beforeClass
in beforeMethod
in test case 1
in afterMethod
in beforeMethod
in test case 2
in afterMethod
in afterClass
in afterTest
in afterSuite

更新于:2022年1月12日

214 次浏览

启动你的职业生涯

通过完成课程获得认证

开始学习
广告