I want to run different sets of steps for different tests in TestNG. Is this possible?
Example:
@BeforeMethod
Method1{
Step 1
Step 2
}
@BeforeMethod
Method2{
Step 3
Step 4
}
@Test
Test1 {
Run Method1 Steps
Test1 Steps;
}
@Test
Test2 {
Run Method2 steps
Test2 steps
}
You can call Method1 and Method2 directly in each test where they are needed, but this approach has a couple of downsides, such as code duplication and polluting the test with extra data that affects test readability (i.e. mixing setup and the test itself in a single method). But it is still ok if it does its job correctly.
As an alternative, I recommend looking at the onlyForGroups attribute of the @BeforeMethod/@AfterMethod annotations. It allows you to run setup/teardown methods only for the test methods with specified groups, so you can separate the test logic from the configuration logic while maintaining good scalability in terms of adding new setup/teardown.
Here is a short example:
Output:
You can control the order of before/after methods either by the 'dependsOnMethod' attribute or by the method name (alphabetical order).