Reputation: 58774
What is the usage of TestNG BeforeMethod's firstTimeOnly optional element?
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).
It seems redundant as using @BeforeTest which is more clear
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.
Upvotes: 0
Views: 655
Reputation: 11958
@BeforeMethod
is invoked before each test, while @BeforeTest
is invoked once, before any test has yet been executed.
So, it makes no sense having a firstTimeOnly
property on @BeforeTest
, it will only ever be executed once per group of tests, by design.
On the other hand, since @BeforeMethod
is possibly executed several times (if test methods are executed several times using invocationCount
), it is possible to tell TestNG to only execute the method annotated with BeforeMethod
once.
This answer has a good example on the difference between the two annotations.
Let's illustrate the behaviour with an example:
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");
}
}
This prints:
before test
before method
executing method one
before method
executing method one
before method
executing method one
Notice that beforeMethod()
is executed before each method, while beforeMethod
is executed once, before any test has yet been executed. Also notice that beforeMethod
is executed before each execution of methodOne()
.
Now, let's add the firstTimeOnly
property:
@BeforeMethod(firstTimeOnly = true)
before test
before method
executing method one
executing method one
before method
executing method one
Now, beforeMethod()
is only executed once before methodOne()
, even though the test is executed twice.
Upvotes: 1