Use different @BeforeMethod methods in TestNG

25 Views Asked by At

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
}
1

There are 1 best solutions below

0
sashkins On

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:

public class DummyTest {


    @BeforeMethod(onlyForGroups = {"testA"})
    public void beforeTestA1() {
        System.out.println("Before Test A executed - 1");
    }


    @BeforeMethod(onlyForGroups = {"testA", "testB"})
    public void beforeTestAB1() {
        System.out.println("Before Test AB executed - 1");
    }


    @BeforeMethod(onlyForGroups = {"testB"})
    public void beforeTestB1() {
        System.out.println("Before Test B executed - 1");
    }


    @BeforeMethod(onlyForGroups = {"testB", "testA"})
    public void beforeTestAB2() {
        System.out.println("Before Test AB executed - 2");
    }


    @Test(groups = {"testA"})
    public void testA() {
        System.out.println("Test A executed");
    }


    @Test(groups = {"testB"})
    public void testB() {
        System.out.println("Test B executed");
    }


}

Output:

Before Test A executed - 1
Before Test AB executed - 1
Before Test AB executed - 2
Test A executed
Before Test AB executed - 1
Before Test AB executed - 2
Before Test B executed - 1
Test B executed

You can control the order of before/after methods either by the 'dependsOnMethod' attribute or by the method name (alphabetical order).