TestNG BeforeMethod 的 firstTimeOnly 用法

TestNG BeforeMethod's firstTimeOnly usage

TestNG BeforeMethod's firstTimeOnly可选元素的用法是什么?

If true and the @Test method about to be run has an invocationCount > 1, this BeforeMethod will only be invoked once (before the first test invocation).

使用@BeforeTest显得多余

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

@BeforeMethodeach 测试之前调用,而 @BeforeTest 在任何测试之前被调用 once尚未被处决。

因此,在 @BeforeTest 上设置 firstTimeOnly 属性 是没有意义的,按照设计,每组测试只会执行一次。

另一方面,由于 @BeforeMethod 可能被执行多次(如果测试方法使用 invocationCount 被执行多次),可以告诉 TestNG 只执行被注释的方法BeforeMethod一次。

This answer 有一个很好的例子说明两个注释之间的区别。

让我们用一个例子来说明这个行为:

public class TestClass {

  @Test(invocationCount = 2)
  public void methodOne() {
    System.out.println("executing method one");
  }

  @Test
  public void methodTwo() {
    System.out.println("executing method one");
  }

  @BeforeMethod
  public void beforeMethod() {
    System.out.println("before method");
  }

  @BeforeTest
  public void beforeTest() {
    System.out.println("before test");
  }

}

这会打印:

before test
before method
executing method one
before method
executing method one
before method
executing method one

注意 beforeMethod() 在每个方法之前执行,而 beforeMethod 在任何测试尚未执行之前执行一次。另请注意 beforeMethod 在每次执行 methodOne().

之前执行

现在,让我们添加 firstTimeOnly 属性:

@BeforeMethod(firstTimeOnly = true)

before test
before method
executing method one
executing method one
before method
executing method one

现在,beforeMethod() 只在 methodOne() 之前执行一次,即使测试执行了两次。